The MVC Pattern and PHP, Part 1

This entry is part 1 of 2 in the series The MVC Pattern and PHP

The MVC Pattern and PHP

The Model-View-Control (MVC) pattern, originally formulated in the late 1970s, is a software architecture pattern built on the basis of keeping the presentation of data separate from the methods that interact with the data. In theory, a well-developed MVC system should allow a front-end developer and a back-end developer to work on the same system without interfering, sharing, or editing files either party is working on.

Even though MVC was originally designed for personal computing, it has been adapted and is widely used by web developers due to its emphasis on separation of concerns, and thus indirectly, reusable code. The pattern encourages the development of modular systems, allowing developers to quickly update, add, or even remove functionality.

In this article, I will go the basic principles of MVC, a run through the definition of the pattern and a quick example of MVC in PHP. This is definitely a read for anyone who has never coding with MVC before or those wanting to brush up on previous MVC development skills.

Understanding MVC

The pattern’s title is a collation of its three core parts: Model, View, and Controller. A visual representation of a complete and correct MVC pattern looks like the following diagram:

MVC Process

The image shows the single flow layout of data, how it’s passed between each component, and finally how the relationship between each component works.

Model

The Model is the name given to the permanent storage of the data used in the overall design. It must allow access for the data to be viewed, or collected and written to, and is the bridge between the View component and the Controller component in the overall pattern.

One important aspect of the Model is that it’s technically “blind” – by this I mean the model has no connection or knowledge of what happens to the data when it is passed to the View or Controller components. It neither calls nor seeks a response from the other parts; its sole purpose is to process data into its permanent storage or seek and prepare data to be passed along to the other parts.

The Model, however, cannot simply be summed up as a database, or a gateway to another system which handles the data process. The Model must act as a gatekeeper to the data itself, asking no questions but accepting all requests which comes its way. Often the most complex part of the MVC system, the Model component is also the pinnacle of the whole system since without it there isn’t a connection between the Controller and the View.

View

The View is where data, requested from the Model, is viewed and its final output is determined. Traditionally in web apps built using MVC, the View is the part of the system where the HTML is generated and displayed. The View also ignites reactions from the user, who then goes on to interact with the Controller. The basic example of this is a button generated by a View, which a user clicks and triggers an action in the Controller.

There are some misconceptions held about View components, particularly by web developers using the MVC pattern to build their application. For example, many mistake the View as having no connection whatsoever to the Model and that all of the data displayed by the View is passed from the Controller. In reality, this flow disregards the theory behind the MVC pattern completely. Fabio Cevasco’s article The CakePHP Framework: Your First Bite demonstrates this confused approach to MVC in the CakePHP framework, an example of the many non-traditional MVC PHP frameworks available:

“It is important to note that in order to correctly apply the MVC architecture, there must be no interaction between models and views: all the logic is handled by controllers“

Furthermore, the description of Views as a template file is inaccurate. However, as Tom Butler points out, this is not one person’s fault but a multitude of errors by a multitude of developers which result in developers learning MVC incorrectly. They then go on to educate others incorrectly. The View is really much more than just a template, however modern MVC inspired frameworks have bastardised the view almost to the point that no one really cares whether or not a framework actually adheres to the correct MVC pattern or not.

It’s also important to remember that the View part is never given data by the Controller. As I mentioned when discussing the Model, there is no direct relationship between the View and the Controller without the Model in between them.

Controller

The final component of the triad is the Controller. Its job is to handle data that the user inputs or submits, and update the Model accordingly. The Controller’s life blood is the user; without user interactions, the Controller has no purpose. It is the only part of the pattern the user should be interacting with.

The Controller can be summed up simply as a collector of information, which then passes it on to the Model to be organized for storage, and does not contain any logic other than that needed to collect the input. The Controller is also only connected to a single View and to a single Model, making it a one way data flow system, with handshakes and signoffs at each point of data exchange.

It’s important to remember the Controller is only given tasks to perform when the user interacts with the View first, and that each Controller function is a trigger, set off by the user’s interaction with the View. The most common mistake made by developers is confusing the Controller for a gateway, and ultimately assigning it functions and responsibilities that the View should have (this is normally a result of the same developer confusing the View component simply as a template). Additionally, it’s a common mistake to give the Controller functions that give it the sole responsibility of crunching, passing, and processing data from the Model to the View, whereas in the MVC pattern this relationship should be kept between the Model and the View.

MVC in PHP

It is possible to write a web application in PHP whose architecture is based on the MVC pattern. Let’s start with a bare bones example:

<?php
class Model
{
    public $string;

    public function __construct(){
        $this->string = "MVC + PHP = Awesome!";
    }
}
<?php
class View
{
    private $model;
    private $controller;

    public function __construct($controller,$model) {
        $this->controller = $controller;
        $this->model = $model;
    }
	
    public function output(){
        return "<p>" . $this->model->string . "</p>";
    }
}
<?php
class Controller
{
    private $model;

    public function __construct($model) {
        $this->model = $model;
    }
}

We have our project started with some very basic classes for each part of the pattern. Now we need to set up the relationships between them:

<?php
$model = new Model();
$controller = new Controller($model);
$view = new View($controller, $model);
echo $view->output();

As you can see in the example above, we don’t have any Controller-specific functionality because we don’t have any user interactions defined with our application. The View holds all of the functionality as the example is purely for display purposes.

Let’s now expand the example to show how we would add functionality to the controller, thereby adding interactivity to the application:

<?php
class Model
{
    public $string;

    public function __construct(){
        $this->string = “MVC + PHP = Awesome, click here!”;
    }

}
<?php
class View
{
    private $model;
    private $controller;

    public function __construct($controller,$model) {
        $this->controller = $controller;
        $this->model = $model;
    }

    public function output() {
        return '<p><a href="mvc.php?action=clicked"' . $this->model->string . "</a></p>";
    }
}
<?php
class Controller
{
    private $model;

    public function __construct($model){
        $this->model = $model;
    }

    public function clicked() {
        $this->model->string = “Updated Data, thanks to MVC and PHP!”
    }
}

We’ve enhanced the application with some basic functionality. Setting up the relationship between our components now looks like this:

<?php
$model = new Model();
$controller = new Controller($model);
$view = new View($controller, $model);

if (isset($_GET['action']) && !empty($_GET['action'])) {
    $controller->{$_GET['action']}();
}

echo $view->output();

Run the code and when you click on the link you’ll be able to see the string change its data.

Conclusion

We’ve covered the basic theory behind the MVC pattern and have produced a very basic MVC application, but we still have a long way to go before we get into any nitty-gritty functionality.

Next up in the series we’ll cover some of the choices you face when trying to create a true MVC application on the web in PHP. Stay tuned!

Image via Fotolia

Comments on this article are closed. Have a question about MVC Patterns and PHP? Why not ask it on our forums?

The MVC Pattern and PHP

The MVC Pattern and PHP, Part 2 >>

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.małolepszy.com dyferencjal

    Nice article. Covers MVC basics very smoothly :).

    Little mistake in case someone wants to copy-paste it:
    public function output() {
    return ‘model->string . ““;
    }

    It will output invalid html “<a href="…"{string from model}.

    • Khthulhu

      dyferencjal:
      You are correct sir. What the anchor code needs is an ending “>” to work. Once I changed the code to:
      return ‘<a href=”MVC.php?action=clicked” rel=”nofollow”>’ . $this->model->string . “</a>”;
      it worked great. Thanks for the heads up!

  • mohsen

    very useful
    please keep

  • http://phpro.ir saeed

    thanks

  • Charlie Norway

    Nice little article that gets to the point quickly ;)

  • http://www.psinas.com Martin Psinas

    Sooo, you’re telling me everything I’ve been learning about MVC over the past several months is wrong. Great. Looking forward to future articles on this topic.

    • http://www.callumhopkins.com Callum Hopkins

      Hi Martin,
      Sorry if you feel that you’re in the position you’ve described, but I would imaging most of what you’ve learnt is actually correct, just maybe one or two things maybe slightly flawed. Part 2 should be coming out with in the next week with some more examples. In my opinion, anything learnt is never a waste, even if it turns out to be slightly flawed. :)
      Thanks

      • http://www.psinas.com Martin Psinas

        Thank you for the vote of confidence, Callum. In trying to wrap my head around this I do have one question. You stated: “It’s also important to remember that the View part is never given data by the Controller.” If that’s the case, then why in your examples are you passing an instance of the Controller to the View?

        • http://www.callumhopkins.co.uk Callum Hopkins

          Hi Martin,
          If you ever find yourself writing a tutorial with example code, make sure you DOUBLE check the code!
          You are indeed correct about the error, and we’ll get the code on both examples updated. In the meantime, if you just remove the passing of the $controller object to the view class and remove the view construct class looking for the $controller object, both the examples will work correctly.

          Again, apologies about this, I will make sure I don’t like a sloppy mistake like this happen again. :)

          Thanks

          • Chris Emerson

            I did wonder that myself! One thing I despise in most MVC frameworks is the view just being an included PHP file with just a bunch of variables in. But then, I also hate smarty and the like – I tend to go for a very light-weight and feature-light templating engine with just the basics.

          • http://www.psinas.com Martin Psinas

            Another thing I’m failing to grasp, which I’m hoping will be cleared up in the next article, you said: “The Controller is also only connected to a single View and to a single Model, making it a one way data flow system.”

            If a user were to submit something to a forum, for example, wouldn’t the request need to access both a user / permissions model in addition to a forum model? Or perhaps you’re suggesting it’s the model’s responsibility to connect to other models if needed? Maybe that’s a bad example but I hope the question makes sense. Again, looking forward to reading more.

          • http://rameezusmani.com Rameez Usmani

            {{If a user were to submit something to a forum, for example, wouldn’t the request need to access both a user / permissions model in addition to a forum model? Or perhaps you’re suggesting it’s the model’s responsibility to connect to other models if needed?}}
            I think it is the controller’s responsibility to access relevant models and construct the proper view. For example if user posted a reply but do not have permission to do so , controller will get Permission Model…check for permissions…then call a view passing error into it.

  • colTony

    Nice article!!! Please move on. :)

  • http://www.adeveloper.org Hossein Baghayi

    MVC pattern was one of the vague things I always had problem with that in which part should I put what.
    By this article I could figure it out to some extend.
    I’m desperately looking forward to the up-coming series.
    Thank you

  • http://sputnik.pl Michal Ty

    I agree with most of what you show (i.e. dependency injection, separation of concerns), but I think view should be separated from templates. One should not mix languages.

  • http://www.alabiansolutions.com Alabi

    Still wrapping this around my head.

  • http://www.adrianmiu.ro/ Adrian Miu

    Looks like most PHP frameworks have got the MVC pattern wrong. At least that what it looks like if you look at the examples they put forth
    1. Views are just templates
    2. Controller actions are just route handlers
    On the other hand creating a special view class for a controller might be an overkill; you still need a template which renders data retrieved from model(s) and the views are state-less (you pass the view to the user and that’s it, there’s no “continous” interaction between the view and the user).

    • teresko

      The ones that “got it wrong”, where people who started pushing RubyOnRails protoytyping framework as “the mvc”. The “experts” who wrote php frameworks just cloned it, without any research in what MVC design pattern really is.

  • http://heymanengineering.com Sam

    Interesting discussing going on here. I’ve always struggle to figure out how the MODEL, VIEW and CONTROLLER work. I’ve finally got to grips with it through Paul Hegarty’s iOS6 development course on iTunes (Stanford University). In the first lecture he gives a thorough and flawless overview of MVC. One thing he makes very clear is that the VIEW and the MODEL DO NOT communicate.
    He also shows how large programs can be split into separate MVCs and how they communicate between each other.
    Hope you find his lecture as helpful as I did, and look forward to further discussions on this forum!

    • http://www.lse.ac.uk/ Garrie

      I found Paul Hegarty’s lecture on YouTube. The link below is to the point in the lecture covering MVC
      http://youtu.be/_CBpdhGPOUQ?t=18m10s

    • tereško

      If your lectures tell you that model layer does not communicate with views, then it is either wrong or you misunderstood it.

      In classical MVC design pattern views observer the model layer structures and get notified, when state of that structure is altered. In web-oriented interpretations of MVC, the views request data from model layer, when they need it.

      In proper MVC and MVC-inspired patterns views DO NOT alter the state of the model layer. But they communicate. Then again … the lectures was for iOS development, so I’m not all that surprised.

  • http://uniquelifecare.com Ashish Makwana

    Hi friends,
    It is very useful for beginner.please keep it and please inform us as link in our email.
    In this mvc structure one of syntax error is find our for incomplete of <a> tag which i have completed.

    public function output() {
    return ‘<a href=”mvc.php?action=clicked” rel=”nofollow”>’.$this->model->string.”</a>”;
    }

    • http://techankit.com ankit

      thanks a lot . . . perfect eg for newbees

  • teresko

    You should also note, that in fully implemented MVC-like design patterns, the Model is actually a complex layer (just like Presentation layer, that contains controller and views .. among other structures). Not any single class. While showing examples of basic structure, it is just fine to have a class called “model”. But in real application the model layer would be composed from structures that are responsible for: application logic, storage logic and domain logic.

    Also you should not that the leaking encapsulation (in form of public variable), should not be used in real world code.

  • http://www.flipflops.org John

    @Sam – Definitely going to try and check out the course you recommend.
    I have always understood that the model and view do not communicate directly too – and that it is the responsibility of the controller to provide the view with the data pulled from the appropriate model(s).

    @callum – It is always useful to see bare bones code and also to have your beliefs challenged. So thank you for an article that is clearly promoting discussion!

  • http://www.tonymarston.net Tony Marston

    I’m afraid that I have to disagree with two points made in this article:

    (1) There must be no interaction between models and views: all the logic is handled by controllers.

    The MVC pattern merely describes 3 separate components and their responsibilities, but is does *NOT* cast in concrete the way that data passes between each of these components. Data may be pulled out of the Model by the Controller, then pushed into the Model. It may be pushed by the Model directly into the View, or it may be pulled out of the Model by the View. *HOW* the data moves is completely irrelevant as that is nothing more than an implementation detail.

    I was party to a similar discussion in a PHP newsgroup several years, and different people tried to dictate a particular method of data movement, and firmly believed that any other method was totally wrong. I repeat, *HOW* the data moves is irrelevant. The only important point is that you have three modules which can be clearly seen to be carrying out the responsibilities of the Model, the View and the Controller.

    (2) The Controller is also only connected to a single Model.

    The fact that most MVC samples only show a single model does *NOT* mean that an implementation of MVC *CANNOT* use more than one Model at a time. In my framework each Model is a class which represents a single database table, and if I have a View which needs to show data from different tables in different areas of the screen then I access a separate Model for each of those areas. For example, I have a screen which lists all sales orders for a single customer, so I have the customer details shown in an area at the top of the screen with rows of order details shown underneath, with pagination options if there are more orders than can fit into a single screen. The CUSTOMER->ORDER relationship is a typical PARENT->CHILD relationship which can occur between many different tables, so is a fairly common type of screen. Not so common is the PARENT->CHILD->GRANDCHILD relationship, but it does exist. The idea that I have to go through a single Model in order to obtain data from multiple tables is both illogical and restrictive, so it is an idea that I refuse to entertain.

  • http://www.xoogu.com/ Dave

    Interesting article, thanks for sharing. I remain to be convinced of the benefits of MVC in my own work, what sort of size projects would you use it for?

    One thing I noticed, in your last code sample you check that $_GET['action'] is set and not empty. You can just check whether it’s not empty, no need for is_set.

  • Monico Briseño

    I have a question.
    Hi, there. This MVC in PHP article written by Callum Hopkins is very interesting. When I was reading it, I found the preposition between in different parts of the it. For example:
    “Setting up the relationship between our components now looks like this:”
    According to the Cambridge Dictionaries Online:
    Between
    Definition: in or into the space that separates two places, people, or objects.
    But I understood the author is mentioned three elements: Model, View and Controller. If so, it would be better use the preposition among.
    Am I wrong?
    Thanks in Advance.
    Cheers

  • http://kuldeepsinghit.in kuldeep singh

    Thanks Callum for this nice article . It is easy to understand of MVC layout. please continue it..

  • Marcelo

    Hi Callum, you stated: “It’s also important to remember that the View part is never given data by the Controller. As I mentioned when discussing the Model, there is no direct relationship between the View and the Controller without the Model in between them.” But what if I just want to display a simple hello world page? Do I have to come with a Model for no reason?

  • http://anichandran.blogspot.com anichandran ayyasamy

    very nice artical. more helful for me, thanks in advance.

  • Kevin21live

    Small mistake in the if statement. it will not work if its not changed.

    Correct code :
    if(isset($_GET['action']) && !empty($_GET['action']))
    {
    $controller = $controller->$_GET['action']();
    }

  • Bill

    Code works fine for me I didn’t alter the if statement.

  • Bogdan Olteanu

    I’ve always stated among my friends that mvc is wrong since the flow of the data is not right and i couldn’t understand the ideea of controller was calling the model and the view and i was like why passing data to the model if i need to return it back to the controller to send it to the view ? instead of sending data to the model then sending it to the view. btw an implementation of the same thing a simple one wouldn’t be user -> controller(inside an instance of model) -> sends data to the model(inside an instance of the view) -> sends data to the view calling the final method there -> output to the browser.

  • Bishnu

    I had a impression that in MVC view shouldn’t directly access Model. But in this example, view is accessing a model’s property in it’s output() function. Can anyone please make me clear?
    Thanks,

  • ajay

    Thanks article ………