There is something about MVC in PHP
3A-STI Students must read !
I will describe all steps required to develop the most tiny MVC pattern ever in PHP:
M:stands for (data) Model V:stands for (data) View C:stands for Controller
Logical schema
Model: The Model encloses the application data.
View: The View element is used for presenting the data of the model to the user. It interacts with the user and presents the result formed by the model
Controller: The entrypoint into the application. It handles the user requests and listens to all the events triggered in the view and prepares the response back. When user request is sent to the controller, it forwards it to the Model to provide some logic on it.
Several important web frameworks have adopted the pattern MVC.
As I said, my goal is to devlop a very tiny MVC from scratch. I hope this guide helps you to find your way through to advanced implementation!
The Model
<?php
class Model {
private $data=null;
public function __construct() {
$this->data="bonjour";
}
public function getData():string {
return $this->data;
}
public function setData(string $data) {
$this->data = $data;
}
}
?>
This simple class is built around a private data member. The Model coud read and set the data. Very easy to grasp.
The Controller
<?php
class Controller {
private $model;
public function __construct(Model $model) {
$this->model=$model;
}
public function update(){
$this->model->setData("Hello");
}
}
?>
The controller is equiped with two methods:
- the constructor which permits to link the Controller with the Model
- the update method to change the member data value
The View
<?php
class View {
private $model;
public function __construct(Model $model) {
$this->model=$model;
}
public function out():string {
return
'<a href="index.php?action=update">'.$this->model->getData().'</a>';
}
}
?>
The View is equiped with two methods:
- the constructor which permits to link the View with the Model
- the out method to get and display the member data value from the Model
The final page is the Home page (index.php):
<?php
//INCLUDES
require __DIR__.'/model.php';
require __DIR__.'/view.php';
require __DIR__.'/controller.php';
//INSTANCIATIONS
$model = new Model();
$view = new View($model);
$controller = new Controller($model);
if(isset($_GET['action'])){
$controller->{$_GET['action']}();
}
echo '<h1>'.$view->out().'</h1>';
?>
Scenario
When you hover the mouse pointer over "Bonjour", you will see the following URL: http://localhost/index.php?action=update
When you click on it, you are asking for an update (action=update). The Model will be updated conformly! accordingly, the view displays the updated data in the browser.
voilà , you get it:
Any question? let me know!