MVC and Code Organization
Learn about the model-view-controller (MVC) design pattern and how to implement it in PHP for better code organization.
We'll cover the following
PHP as a programming language is easy to learn and implement. However, it’s also a language that can easily deteriorate into spaghetti code—different types of code all jumbled and tangled with no clear point of entry. Because PHP is often used in conjunction with HTML, CSS, and JavaScript, it’s more likely to be part of spaghetti code. It’s not recommended to write spaghetti code because it’s much harder to maintain and change, not to mention treating its bugs.
To prevent the deterioration of our code into spaghetti code, we organize our code into files and folders. A good question to ask here is how we can separate the logical part that PHP is responsible for from the template part in which HTML is the main component. The simplest way is to put the application’s logic (in which we handle the variables and determine their values) into one file or folder while embedding the variables into the HTML elsewhere in the application.
Note: The logical part of the application is known as the controller, while the template part is known as the view.
In the example given below, the controller.php
file is used as the controller in the application. It receives data from the data source (database, external API, and so on), processes it, and provides the variables that can later be used in the template file.
The data that was retrieved from the data source is grouped in a $cars
array that holds the cars’ models and prices. We check to see if the price is expensive with the expensiveOrNot()
function and store the data in a new array with the name of $carsReviewed
.
Get hands-on with 1400+ tech skills courses.