The MVC Pattern Explained
Warning: This post is old and reflects my (limited) knowledge at the time of writing, some of this is wrong.
Prerequisites
In this article I assume that you know basic PHP things like variables, functions, loops, arrays, classes and at least a little bit about how PHP interacts with databases.
First, a horrible example!
I remember when I was starting out with PHP and tried to make my first dynamic website.
I started out trying to create my own little blog, which is a simple little task that most people try to do when they are starting out.
I was doing inline database queries and had horrible spaghetti code everywhere... but it worked, kind of...
...until I wanted to update it a little, by that point the site had a lot of PHP files that did all sorts of stuff, but they all had a database query inside of them that connected to the database, fetched some records and displayed them on the page.
To update the site with the functionality that I wanted I had to rewrite all of the database queries, in 10~ separate PHP files, this quickly became annoying and tedious.
Here is an example:
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>My 10 latest blog posts</h1>
<div class="posts">
<?php
$con = mysqli\_connect("localhost", "username", "password", "database") ;
$result = mysqli\_query($con, "SELECT \* FROM posts LIMIT 10")
if ($result) {
while ($row = mysqli\_fetch\_assoc($result)) {
echo "<h1>"
. $row\["heading"\]
. "</h1>"
. "<h3>"
. $row\["subheading"\]
. "</h3>"
. "<div class="content">"
. $row\["content"\]
. "</div>";
}
} else {
die(mysqli\_error($con));
}
?>
</div>
</body>
This kind of code is hard to update because your database queries are inside of the file that also displays the HTML.
Imagine if you had a 50 page website where every page was written in a procedural style like the example above, now imagine that the password for the database changed and you as the web developer has to go into that mess of a website and change the line $con = mysqli_connect("localhost", "username", "password", "database"); in EVERY PAGE! ( to be fair, search replace in all would do the trick, BUT STILL!)
Fuck that, don't create such a mess for yourself or anyone else for that matter.
So, how do we combat horrible spaghetti code and inline database queries?
Enter the MVC Pattern!
So what exactly is an MVC Pattern and how does it help us write more maintainable code?
MVC stands for Model View Controller, and you've probably already read that on various other articles you've tried to read but didn't understand, don't be discouraged, I didn't understand it either when I was starting out, but whatever, let's give you knowledge that you can actually use.
The primary objective of using the MVC pattern is to separate the code that interacts with the database, presentation(think of it like the html and css stuff) and "routing" into maintainable chunks of code, Imagine that you had a folder with your website in it, then you make 3 subfolders called model, view, controller.
In the model folder is where you would place all the files that handles interaction with the database, by that I mean that if you need to login a user, you should have a controller that handles the post or get request, and feeds the necessary information onto a function somewhere inside your model folder, the function should take the user input(username and password), checks if the username exists and if the password match the one in the database and return TRUE if the user exists or FALSE if it does not.
Once the value is returned it is up to the controller to decide the appropriate course of action, if the user provided the correct username and password the Controller would set a session variable(or something like that) and redirect the user to his account page.
In the account page all relevant information about the user's account will be displayed to him through a view that is located in the views folder, think of a view as an HTML template, to display information in your view that you get from the model/database you would pass it as a variable from the controller, here is how it is done in the popular MVC framework CodeIgniter:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
You can read the CodeIgniter user guide here, I highly encourage you to check it out, it will give you some more technical knowledge about how the MVC pattern works.
Enter the MVC Frameworks!
Now, that you kind of understand the basics of MVC, how should you go about implementing it in your own projects?
Well, you could go out and try to make your own mess of a library/framework and use that in every project, but that is not really a good idea since it minimizes the amount of people who can help you once you run into an issue with your code, making your own MVC framework is a great way to learn, but I'd suggest using a popular framework for commercial projects.
The easiest way to start to use the MVC pattern, and also the smartest way in my opinion is to start getting familiar with an MVC framework that is decently popular and has an active and helpful community, nowadays that seems to be what Laravel is, although I have not used it myself, I'd recommend that you learn that, as it's becoming increasingly popular (Popular = lots of people who can help me when I am stuck).
I use CodeIgniter myself, as I find that it's more "pure" in the sense that it's very lightweight, the syntax is very clean and beautiful (which is important since I'm going to be writing it all day long), easy to modify and that there is no voodoo magic going on behind the scenes, if you understand PHP you should be able to understand the source code of CodeIgniter.
Some might also say that CodeIgniter is the easiest MVC framework to learn, although I wouldn't know as I have not tried any other MVC frameworks.
There are a lot of MVC frameworks out there on the internet, they each have their strengths and weaknesses, I'll list a few of the most popular ones and you can go out and research them yourself.
Conclusion
As you can see, by using the MVC pattern everything will be nicely structured and easy to update at a later time by either yourself or another web developer, the MVC pattern also help you minimize the amount of spaghetti code that you'll write.
Now that doesn't sound so bad now does it? No voodoo magic or bullshit buzzwords here :)