The MVC Pattern and PHP, Part 1

Share this article

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. PHP & MySQL: Novice to Ninja

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?

Frequently Asked Questions (FAQs) about PHP MVC Pattern

What is the significance of the MVC pattern in PHP?

The Model-View-Controller (MVC) pattern is a design pattern that separates an application into three interconnected components. This separation allows developers to modify or update one component without affecting the others. In PHP, the MVC pattern is particularly beneficial because it organizes the code, making it easier to maintain and scale. It also improves the efficiency of data management and user interface design.

How does the MVC pattern work in PHP?

In PHP, the MVC pattern works by dividing the application into three components. The Model handles the data and business logic, the View manages the user interface and presentation of data, and the Controller handles user requests and updates the Model and View accordingly. This separation of concerns allows for more efficient code management and easier debugging.

How can I implement the MVC pattern in my PHP project?

Implementing the MVC pattern in your PHP project involves creating separate files or classes for the Model, View, and Controller. The Model will contain functions for accessing and manipulating data, the View will contain HTML and PHP code for displaying data, and the Controller will contain functions for handling user input and updating the Model and View.

What are some popular PHP MVC frameworks?

There are several popular PHP MVC frameworks that can help you implement the MVC pattern in your projects. These include Laravel, Symfony, CodeIgniter, and CakePHP. These frameworks provide a structured and efficient way to build web applications using the MVC pattern.

What are the benefits of using a PHP MVC framework?

Using a PHP MVC framework provides several benefits. It provides a structured way to organize your code, making it easier to maintain and scale. It also provides built-in functions and libraries for common tasks, reducing the amount of code you need to write. Additionally, MVC frameworks often include security features that protect your application from common web vulnerabilities.

How does the Controller interact with the Model and View in PHP MVC?

In PHP MVC, the Controller acts as an intermediary between the Model and View. When a user makes a request, the Controller interprets the request and calls the appropriate Model functions to process the data. It then updates the View to reflect any changes in the data.

How can I handle user input in PHP MVC?

In PHP MVC, user input is typically handled by the Controller. The Controller receives the user input, validates it, and then passes it to the Model for processing. The Model then updates the data and notifies the Controller, which in turn updates the View.

How can I display data in the View in PHP MVC?

In PHP MVC, data is displayed in the View through the use of PHP and HTML code. The Controller retrieves the data from the Model and passes it to the View, which then generates the HTML to display the data.

How can I update data in the Model in PHP MVC?

In PHP MVC, data in the Model is updated through functions that are called by the Controller. These functions can include operations such as creating, reading, updating, and deleting data.

How can I ensure my PHP MVC application is secure?

Ensuring your PHP MVC application is secure involves several steps. These include validating and sanitizing user input, using prepared statements or parameterized queries to prevent SQL injection, and using built-in security features of your MVC framework. It’s also important to keep your framework and any dependencies up to date to protect against known vulnerabilities.

Callum HopkinsCallum Hopkins
View Author

Callum Hopkins is a designer and front-end developer with over 6 years web experience and has a Bachelors degree in Design for Digital Media. With knowledge in both design and development he is able to influence both sides of the web building process, and has a love for complex coding functions and beautiful design. Callum works as a developer for Deer Digital LTD and runs his own personal blog at callumeuanhopkins.co.uk where he writes thought provoking articles.

gitCSIntermediate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week