MVC (model, view, controller) PHP edition
The advantages of data layers and separation of concerns in programming websites
What is MVC
The model, view, and controller (MVC) is an architectural pattern used to organize the separation of concerns (a modular approach) in Web Development. With MVC, the data and application logic are decoupled (independent).
This separation increases the maintainability/extensibility of your project by keeping the code organized into modules that implement specific functionality.
In this article, I will discuss MVC in the context of the PHP
programming language. I recently used PHP
- along with the usual front-end technologies like JavaScript
, HTML
and CSS
- for my multipage personal website.
I programmed a router that took the user to a new page depending on the current query string. This data was accessed by the $_GET
superglobal variable. I put the code in separate files, page-router.php
and functions.php
. Here’s a snippet of some of the code:
//page-router.php
<?php
/*main page router*/
switch (getPage()) {
case "home":
include "pages/home.php";
break;
case "projects":
include "pages/projects.php";
break;
default:
include "pages/404.php";
}
?>
//functions.php
<?php
function getPage() {
$page = $_GET["page"] ?? null;
return $page;
}
function generateSkills(array $skills) {
foreach ($skills as $key => $value)
echo "<li>" . "<span class='language'>$key</span> " . $value . "</li>";
}
//get all projects
function getAllProjects() {
//get the project data
$json = file_get_contents("database/projects.json");
//decode data to PHP
return json_decode($json, true);
//return data
}
function getProjectBySlug($slug) {
$projects = getAllProjects();
foreach($projects as $project) {
if ($project["slug"] === $slug) {
return $project;
}
}
}
?>
Thanks to MVC I separated out the logic and pages into separate files, and my code is modular and reusable. Qualities that are especially useful for multipage websites with lots of repeating info/components like headers, footers, and site menus to name a few!
An example of the model logic is the getAllProjects
and getProjectBySlug($slug)
functions. These handle the logic for getting the projects from the database and decoding it from JSON
to a PHP
associative array.
The generateSkills(array $skills)
function is an example of view logic. Thanks to type declarations, this function expects an array
as a parameter (otherwise it throws a TypeError). It loops over an array of $skills
and generates the $skills
as HTML elements (using li
and span
).
The control logic can be seen in page-router.php. The user is sent to a page depending on the value of the query parameter. Speaking of logic, now seems a good time to discuss the layers of a website and the advantages of decoupling your program data and logic.
The layers
Websites and applications aren’t built by one developer, nor are they written as singular blocks of monolithic code. There are layers to websites, and depending on the company/working style, are often built/tested/iterated by different Developers simultaneously.
Let’s discuss the different layers of a website, with snippets of code from my personal website as an example:
Presentation Layer (UI Layer):
Accessible via the browser/application, the presentation layer is responsible for the user interface of the application that users interact with. Closely tied to the front end of the website, this layer is the realm of everything related to the visual and interactive aspects of the project.
The languages we use to program this layer are the familiar web technologies such as
HTML
,CSS
,JavaScript
, and user interface components such as forms, buttons, menus, etc.
The primary goal of the presentation layer is to present data and facilitate user interactions.
Application Logic Layer:
This layer contains the application's business logic (the internal rules needed to program behavior), rules, and processing logic.
It handles user input, processes requests, and decides how data should be manipulated or transformed based on the requirements of the business.
This layer can include server-side scripting languages like
PHP
,Python
,Ruby
, etc., and the corresponding code that handles the application’s functionality.The logic layer is in functions.php. Here is the logic to render the global menu. I have slightly different menus depending on the current page
//functions.php function globalNav() { include "database/nav-data.php"; $globalLinks = ["home", "about", "projects", "experiments"]; foreach($navLinks as $navLinkText => $navLink) { if ( in_array($navLinkText, $globalLinks) ) { echo " " . "<a href='$navLink' " . styleAnchorLink($navLinkText) . ">" . $navLinkText . "</a>"; } } }
Data Layer:
The Data Layer is responsible for managing the application's data storage, retrieval, and manipulation. It includes databases, data models, and interaction with storage systems.
Common technologies used in this layer are
SQL
databases likeMySQL
,PostgreSQL
, andNoSQL
databases likeMongoDB
.The data layer is in the databases folder. Here’s an example in case-studies.json
[ { "title": "responsive layout-case study", "slug": "responsive-layout-cs", "id": 0, "hypothesis": "hypothesis: responsiv elayout case study", "conclusion": "conclusion: responsive layout conclusion" }, { "title": "theming challenge", "slug": "theming-challenge-cs", "id": 1, "hypothesis": "hypothesis: theming challenge", "conclusion": "conclusion: theming challenge" } ]
Integration Layer (Service Layer):
The Integration Layer facilitates communication between different parts of the application, as well as with external services or APIs.
It also can handle tasks like data synchronization, API requests, and responses. This layer helps components of the application work together seamlessly.
Security Layer:
The Security Layer is responsible for handling authentication, authorization, and other security-related aspects of the application.
It ensures that only authorized users can access certain parts of the application and that data remains secure.
Infrastructure Layer:
The Infrastructure Layer includes the underlying technologies and services that support the application, such as servers, hosting, networking, and cloud services.
When we talk about coupling in programming, it refers to the intrinsic way the data or logic are tied together, inseparable from each other. Take the following HTML
for example.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
The HTML
and data (items 1,2, and 3) are coupled with each other. And if you wanted to repeat this list across pages you would have to do a lot of copy and pasting. If only there was a better way…
The opposite of coupled is decoupled. Take the following example, same data but using PHP
this time. Below we have an associate array of data. Instead of combining the data and the HTML
, the data is decoupled into an associative array of items.
$data = [
“Item 1”,
“Item 2”,
“Item 3”
];
Summary
When we use frameworks like MVC and think in website layers, we ensure that our website/application has a solid foundation for current and future development. This benefits both the Developer and the User.
Resources
Code
Personal website- coming soon