What is the MVC Pattern?
MVC (Model-View-Controller) is an architectural pattern used mostly in many OOP frameworks, like Laravel or Symfony, to break up code into three logical components that serve very specific purposes. Those components are:
- model – represents the data or business logic.
- view – the visualization of the data to the client (browser) or presentation logic.
- controller – handles the request, process data, and load the appropriate view.
Let’s see the MVC interaction in the diagram below:
Now, it’s the time for a quick demo.
MVC Demo
In this demo, we’ll be printing the student info.
Let’s create a simple .php file that will link the model to the view (this is a controller).
student.php
<?php
// Make the model available
include 'StudentModel.php';
// Create an instance
$studentModel = new StudentModel();
// Get the list of student
$studentList = $studentModel ->getAllStudents();
// Show the view
include 'student-list.php';
We can create a class that represents our model.
StudentModel.php
<?php
class StudentModel
{
// Because we don't have a db, let's hard code data
private $data = array(
"abel" => array(
"fullName" => "Abel Mbula" ,
"point" => 90,
"grade" => "A"
),
"pati" => array(
"fullName" => "Patience Kavira" ,
"point" => 80,
"grade" => "B"
),
"salimas" => array(
"fullName" => "Sarah Lifaefi" ,
"point" => 95,
"grade" => "A"
)
)
function getAllStudent() {
return $data;
}
}
Since what we’re doing is simple, we only have one method (getAllStudent), but you can add as many as you want.
Now, we can create our view.
student-list.php
<?php foreach ($studentList as $key => $student): ?>
- Name: <?= $student['fullName']; ?>,
Point: <?= $student["point"]; ?>,
Grade: <?= $student["grade"]; ?><br>
<?php endforeach; ?>
Let’s put everything together and see how it works.
student.php
index.php
student-list.php
StudentModel.php
<?php foreach ($studentList as $key => $student): ?>- Name: <?= $student['fullName']; ?>,Point: <?= $student["point"]; ?>,Grade: <?= $student["grade"]; ?><br><?php endforeach; ?>