Home >Backend Development >PHP Tutorial >PHP Master | The MVC Pattern and PHP, Part 1
Detailed explanation of Model-View-Controller (MVC) architecture model and PHP implementation example
Core points
The MVC model was originally proposed in the late 1970s and is a software architecture model based on separating the display of data from the methods of interacting with data. In theory, a well-established MVC system should allow front-end developers and back-end developers to work on the same system without interfering with each other, sharing or editing files that either party is processing. Although MVC was originally designed for personal computing, it has been widely adopted by web developers due to its emphasis on separation of concerns, and indirectly, reusable code. This model encourages the development of modular systems, allowing developers to quickly update, add or even delete features. In this article, I will introduce the basic principles of MVC, give an overview of the definition of this pattern, and quickly introduce an example of MVC in PHP. This post is definitely for anyone who has never used MVC to code before, or those who want to review their previous MVC development skills.
Understanding MVC
The name of this pattern is a combination of its three core parts: Model, View, and Controller. The visual representation of a complete and correct MVC pattern is as follows:
This diagram shows the one-way flow layout of data, how data is passed between components, and how it works between components.
Model (Model)
Model refers to the permanent storage of data used in the overall design. It must allow access to the data to be viewed or collected and written and is a bridge between the view component and the controller component in MVC mode. An important aspect of the model is that it is technically "blind" - I mean the model is not connected or understood with what happens after the data is passed to the view or controller component. It neither calls nor seeks responses from other parts; its sole purpose is to process the data into its permanent storage, or to find and prepare the data to be passed to other parts. However, the model cannot be simply generalized as a database, or gateway to another system that processes the data process. The model must act as the gatekeeper of the data, asking no questions, but accepting all requests. Model components are usually the most complex part of the MVC system and are also the core of the entire system, because without it, there is no connection between the controller and the view.
View (View)
Theview is where the data requested from the model and determines its final output. Traditionally, in web applications built using MVC, views are the system part of generating and displaying HTML. The view will also trigger a user's reaction, and the user will continue to interact with the controller. A basic example is a button generated by a view that the user clicks and triggers an action in the controller. There are some misunderstandings about view components, especially web developers who build their applications using the MVC pattern. For example, many people mistakenly believe that the view has no connection to the model and that all the data displayed by the view is passed from the controller. In fact, this process completely ignores the theory behind the MVC pattern. Fabio Cevasco's article "CakePHP Framework: Your First Try" shows this obfuscation approach to MVC in the CakePHP Framework, an example of many non-traditional MVC PHP frameworks available:
"It should be noted that in order to correctly apply the MVC architecture, there is no interaction between the model and the view: all logic is handled by the controller"
In addition, it is inaccurate to describe the view as a template file. However, as Tom Butler points out, this is not a person’s fault, but a lot of mistakes made by many developers, which leads to developers’ incorrect learning of MVC. Then they continue to educate others incorrectly. Views are actually much more than a template, but modern MVC-inspired frameworks have made views so unrecognizable that no one really cares whether the framework really follows the right MVC pattern. It is also important to remember that the view part never receives data from the controller. As I mentioned when discussing the model, without an intermediate model, there is no direct relationship between the view and the controller.
Controller (Controller)
The last component of a triple is the controller. Its job is to process the data entered or submitted by the user and update the model accordingly. The lifeline of the controller is the user; without user interaction, the controller has no purpose. It is the only part of the pattern that the user should interact with. The controller can be simply generalized as a collector of information, which is then passed to the model for organization for storage, and does not contain any other logic than the logic required to collect input. The controller is also connected only to a single view and a single model, making it a one-way data flow system, with handshakes and signatures at each data exchange point. It is important to remember that the controller will only get instructions to perform tasks when the user first interacts with the view, and that the functions of each controller are triggers triggered by the user's interaction with the view. The most common mistake a developer makes is to mistake the controller for a gateway and ultimately assign the functionality and responsibilities that the view should assume (this is usually the result of the same developer simply mistakenly considering the view component as a template). Furthermore, a common mistake is to provide the controller with functionality to be responsible for the compression, delivery and processing of data from the model to the view alone, and in MVC mode, this relationship should be kept between the model and the view.
MVC in PHP
PHP web applications can be written using an MVC-based architecture. Let's start with a simple example:
<code class="language-php"><?php class Model { public $string; public function __construct() { $this->string = "MVC + PHP = Awesome!"; } }</code>
<code class="language-php"><?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>"; } }</code>
<code class="language-php"><?php class Controller { private $model; public function __construct($model) { $this->model = $model; } }</code>
We have started a project with some very basic classes for each schema section. Now we need to set the relationship between them:
<code class="language-php"><?php $model = new Model(); $controller = new Controller($model); $view = new View($controller, $model); echo $view->output();</code>
As you can see in the example above, we don't have any controller-specific features as we don't define any user interaction for our application. The view contains all functions, as the example is purely for display purposes. Now let's expand the example to show how to add functionality to the controller to add interactivity to the application:
<code class="language-php"><?php class Model { public $string; public function __construct() { $this->string = "MVC + PHP = Awesome, click here!"; } public function updateString($newString) { $this->string = $newString; } }</code>
<code class="language-php"><?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="https://www.php.cn/link/5ca1b0a18c411c3ebfc35c9dad7da921">' . $this->model->string . "</a></p>"; } }</code>
<code class="language-php"><?php class Controller { private $model; public function __construct($model) { $this->model = $model; } public function clicked() { $this->model->updateString("Updated Data, thanks to MVC and PHP!"); } }</code>
We enhanced the application with some basic features. Now set the relationship between components as follows:
<code class="language-php"><?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();</code>
Run the code and when you click on the link you will be able to see the string change its data.
Conclusion
We have introduced the basic theory behind the MVC pattern and created a very basic MVC application, but we still have a long way to go before we get into any meticulous features. In the next article in this series, we will cover some of the options you face when trying to create a real MVC application on PHP's web. Stay tuned! Picture from Fotolia Comments in this article have been closed. Are there any problems with MVC mode and PHP? Why not ask questions on our forum?
FAQ for PHP MVC Mode (FAQ)
Model-View-Controller (MVC) mode is a design pattern that divides an application into three interrelated components. This separation allows developers to modify or update one component without affecting others. In PHP, MVC pattern is especially useful because it organizes code and makes it easier to maintain and scale. It can also improve the efficiency of data management and user interface design.
In PHP, MVC mode works by dividing the application into three components. The model processes data and business logic, the view manages the rendering of the user interface and data, and the controller processes user requests and updates the model and view accordingly. This separation of concerns allows more efficient code management and easier debugging.
Implementing MVC mode in a PHP project involves creating separate files or classes for models, views, and controllers. 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 processing user input and updating models and views.
There are several popular PHP MVC frameworks that can help you implement the MVC pattern in your project. These include Laravel, Symfony, CodeIgniter and CakePHP. These frameworks provide a structured and efficient way to build web applications using MVC pattern.
Using the PHP MVC framework provides many 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, the MVC framework often includes security features that protect your applications from common web vulnerabilities.
In PHP MVC, the controller acts as an intermediary between the model and the view. When the user makes a request, the controller interprets the request and calls the corresponding model function to process the data. It then updates the view to reflect any changes in the data.
In PHP MVC, user input is usually processed by the controller. The controller receives user input, verifies it, and passes it to the model for processing. The model then updates the data and notifies the controller, which in turn updates the view.
In PHP MVC, data is displayed in the view by using PHP and HTML code. The controller retrieves data from the model and passes it to the view, and the view generates HTML to display the data.
In PHP MVC, data in the model is updated through functions called by the controller. These functions can include operations such as creating, reading, updating, and deleting data.
Making your PHP MVC application safe involves multiple steps. These steps include validating and cleaning up user input, using prepared statements or parameterized queries to prevent SQL injection, and using built-in security features of the MVC framework. It is also important to keep your framework and any dependencies up to date to prevent known vulnerabilities.
The above is the detailed content of PHP Master | The MVC Pattern and PHP, Part 1. For more information, please follow other related articles on the PHP Chinese website!