Design patterns Part IV – MVC

The problem:

When your php application became larger, you might find yourself in the situation where you don’t know where to change the design of a certain page, or you might have to change in multiple places to get the same results.
For example, if you want to implement a comments system in your application, you could write a all the code in a single php script, which handles comments listing, adding new comments and all the application logic.

But if the client decide to change the layout of the comments listing, you will see how difficult it is to change all the code that display the comment listing. The same goes if the client decide to change something in the application logic (like storing the data in flat files instead of database tables or adding new fields to the comments).

The solution:

Rather than write the whole application in one script, you should split into three parts:

  • A part to handle the application logic (the model)
  • A part to handle the data displaying (the view)
  • The controller which is the communication interface between model and view

In this way, you can easily change over one part of the application (like changing the html layout), without influence on other components.

Today, many frameworks allows writing code applying the mvc pattern, so you should use this in your advantage.

Related posts:

  1. Design Patterns Part II – Factory
  2. Design patterns Part I – Singleton
  3. Design Pattern Part III – Observer

3 Responses to “Design patterns Part IV – MVC”

  1. Rama says:

    – A part to handle the application logic (the model)
    Typically model represents that Data Model rather than application logic.
    Example: In Java EE world, Session beans handle application logic – session beans are not considered as Model.

  2. Ian says:

    My MVC definition is closer to what Rama suggested. Of course, MVC must be adapted to different code environments (MVC for desktop development is very different than for the web), but I typically suggest the following to those new to MVC:

    Model – Abstracts away your external resources or concepts into a class which acts as an API. Think “model” literally

    View – The template or UI later that users view.

    Controller – This is the glue between the model and view. It makes calls to models, manipulates the responses, and pushes data ready for rendering out to the view.

  3. mario says:

    MVC is an overused phrase. What you’re describing is PMVC or MVP.

Leave a Reply