Documente Academic
Documente Profesional
Documente Cultură
PHP
Model View Controller
Rz Rasel
Rz Rasel
1st Edition
Rz Rasel
Rz Rasel
Copyright by Rz Rasel
All rights reserved. No part of this book may be reproduced, distributed, or transmitted in
any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the writer, except in the case of brief
quotations embodied in critical reviews and certain other noncommercial uses permitted by
copyright law. For permission requests, write to the writer, addressed Attention: Permissions
Coordinator, at the address below.
rzandapp@gmail.com
Rz Rasel
REDITS
Others
Callum Hopkins
Kasia Mikoluk
Tom Butler
Pablo Pastor
Rz Rasel
bout author
Rz Rasel unearthed the World Wide Web and started creating web sites many years. Working
in software frim in bangladesh as android developer, web developer with system analysis and
design, database design. Write blogs in google blogger, WordPress (https://arzrasel.wordpress.com). A few years later, Rz Rasel created his first blog (https://arzrasel.wordpress.com).
In his spare time, he enjoys to write story, poem. You can visit his home page at https://arzrasel.wordpress.com or e-mail him at rzandapp@gmail.com.
Rz Rasel
Rz Rasel
uthors Note
When I am trying to learn about Model View Controller (MVC) I dont get any proper or complete book for MVC. I get a lot of book about Model View Controller (MVC), but that are not
for pure Model View Controller (MVC). That books are mixed with existing MVC framework.
So its hard to me for properly learn about Model View Controller (MVC) and how Model
View Controller (MVC) works and designed. But at last I can learn Model View Controller
(MVC). Personally I am trying to make a hand note whatever I learn about MVC. And now
I put all together my hand note I am trying to help all of them who want/interested to learn
about MVC.
Rz Rasel
Rz Rasel
et In Touch
Rz Rasel
Rz Rasel
ontents
01
02
03
MVC Architecture
MVC Basic Architecture. . . . . . . . . . . . . . . . . . . . . . .
The model. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The controller . . . . . . . . . . . . . . . . . . . . . . . . . . .
15
15
15
16
18
18
18
19
23
23
23
24
24
24
24
25
25
25
26
26
27
27
28
28
29
29
30
Rz Rasel
ontents
04
05
32
32
33
34
34
35
35
35
35
35
36
36
36
37
37
38
39
39
40
41
41
41
44
44
44
44
44
45
45
45
46
Rz Rasel
ontents
00
06
07
08
Code snippet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . . 47
MVC little history and Web Applications
MVC little history . . . . . . . . . . . . . . . . . . . . . . . . . .
MVC for Web Applications . . . . . . . . . . . . . . . . . . . . . .
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Lets See an Example . . . . . . . . . . . . . . . . . . . . . . . .
What are the Advantages? . . . . . . . . . . . . . . . . . . . . .
Ok, but Why a Framework?. . . . . . . . . . . . . . . . . . . . .
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
51
51
52
52
52
52
53
54
55
56
56
57
59
61
61
62
64
64
65
66
66
67
69
69
Rz Rasel
ontents
09
10
72
72
72
72
73
73
73
73
74
74
74
74
75
75
75
76
76
80
81
82
83
84
84
85
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Rz Rasel
Rz Rasel
ontents
01
MVC Architecture
MVC Basic Architecture. . . . . . . . . . . . . . . . . . . . . . .
The model. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The controller . . . . . . . . . . . . . . . . . . . . . . . . . . .
15
15
15
16
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 01
Page - 14
Rz Rasel
User
Controller
View
Model
The model
The model is responsible for managing the data of the application. It responds to the request
from the view and it also responds to instructions from the controller to update itself.
The view
A presentation of data in a particular format, triggered by a controllers decision to present the
Chapter - 01
Page - 15
Rz Rasel
Chapter - 01
Page - 16
Rz Rasel
ontents
02
18
18
18
19
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 02
Page - 17
Rz Rasel
Rz Rasel
CONTROLLER
USER
MODEL
VIEW
Heres a crude analogy: the muscles, bones and organs in your body are the model that holds
everything vital. The skin, hair, etc. are the view that controls the outward representation
of the muscles and bones (the model). Your senses are the controller that helps the model
interact with the world.
Want to make web applications? Learn dynamic web programming with PHP in this course.
MVC in PHP
As a programmer, youll most likely to encounter MVC in a Ruby on Rails or Django project.
However, it is also used in some PHP web frameworks, though the implementation isnt nearly
always uniform or in strict accordance with the theoretical foundation of MVC as laid down by
Ted Kaehler.
CakePHP, which is one of the most popular PHP frameworks, uses an interpretation of the
Ruby on Rails MVC pattern. If you download a copy of the framework, youll see the following
directory structure in
/app/:
Chapter - 02
Page - 19
Rz Rasel
..
Elements
Emails
Errors
Helper
Layouts
Pages
Scaffolds
/Model/:
..
Behavior
Datasource
AppModel.php
And /Controller/:
Chapter - 02
Page - 20
Rz Rasel
..
cache
config
controllers
core
errors
helpers
hooks
language
libraries
logs
modesl
third_party
views
.htaccess
index.php
However, CakePHP and CodeIgniters approach isnt pure MVC, for here, the view and the
model can interact with each other. In a pure MVC, all interactions must be handled by the
controller alone. Most frameworks CakePHP included tend to treat the View as little more
than a CSS template that controls the way the web page/app looks. The MVC approach is typically muddled in most PHP frameworks, both because of a poor translation of the Ruby on Rails
and other similar frameworks.
MVC is an abstract, theoretical topic that can be difficult to grasp for beginners. You can learn
more about it in this course on PHP programming from scratch.
rzandapp@gmail.com
If youve got suggestions for improvements Id love to see. Dont hesitate.
IF ITS HELP YOU PLEASE LEAVE A COMMENT AND LET ME KNOW. ID LOVE TO
HEAR.
Feel Free To Send More Feedback Or Question You May Have.
z
Chapter - 02
Page - 21
Rz Rasel
ontents
03
23
23
23
24
24
24
24
25
25
25
26
26
27
27
28
28
29
29
30
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 03
Page - 22
Rz Rasel
Chapter - 03
Page - 23
Rz Rasel
Chapter - 03
Page - 24
Rz Rasel
Chapter - 03
Page - 25
Rz Rasel
Chapter - 03
Page - 26
Rz Rasel
private $model;
public function __construct(UserListModel $model)
{
$this->model = $model;
}
public function search($criteria)
{
$this->model->filterByName($critiera);
}
Clean, empty controller code. Absent of both the views display logic and the models domain
logic. One thing to note here is that the controller does not require access to its view, only the
model. This is because in MVC, the only reason a controller needs access to the view is for
the observer pattern: to inform the view to refresh from the model. In PHP this is a non-issue
because the view must have been refreshed anyway.
A simplistic model would look something like this:
PHP Code
class UserListModel
{
private $searchName;
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
public function filterByName($name)
{
$this->searchName = $name;
}
public function getUsers()
{
//Find the selected users.
return $this->db->query(SELECT * FROM users WHERE name like :name, array(:name, $this>searchName);
}
}
The important part to note here is that the model has a state, in this example, the name which
has been searched for. In most pseudo-MVC frameworks the model has no state, the state is
retained in the controller. This seemingly trivial fact is actually the core of the problem: the
view needs to know about this state. This is why the erroneous controller as a mediator architecture has developed.
The view then fetches the data from its model. In this example the usage of a basic template
system has been assumed:
PHP Code
class UserListView
Chapter - 03
Page - 27
Rz Rasel
private $model;
private $template;
public function __construct(UserListModel $model, Template $template)
{
$this->model = $model;
$this->template = $template;
}
public function output()
{
$this->template->assign(users, $this->model->getUsers());
return $template->output();
}
The view has become reusable anywhere a list of users is required. Substitute the model,
which can supply any dataset from any source, it doesnt have to be a database. As long as
the model supplies a list of users the controller is agnostic about where they come from or any
knowledge about what them at all. This promotes robust code by making each component (the
model, view and controller) entirely interchangeable. This is possible because it enforces
the strict separation of concerns that MVC strives for. The controller has no knowledge of how
the view works. From an OOP perspective this is ideal as there is complete encapsulation. The
view can be substituted and it will never break the controller, the controller can be substituted
and it will never break the view.
However, the goal here is reusability. Is the logic behind a listing a set of users any different
to listing a set of blogs, albums, products, etc? No, so why cant that logic be reused? A few
simple amends and it can:
Firstly, some interfaces are defined in order to enforce an API:
PHP Code
interface Listable
{
public function getData();
}
interface Searchable
{
public function setCriteria($criteria);
}
Its now possible to create several models which use these interfaces:
PHP Code
class UserModel implements Listable, Searchable
{
private $searchName;
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
Chapter - 03
Page - 28
Rz Rasel
Chapter - 03
Page - 29
Rz Rasel
Chapter - 03
Page - 30
Rz Rasel
ontents
04
32
32
33
34
34
35
35
35
35
35
36
36
36
37
37
38
39
39
40
41
41
41
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 04
Page - 31
Rz Rasel
Chapter - 04
Page - 32
Rz Rasel
Firstly, the binding logic mentioned has simply been moved into the view. Secondly, and more
importantly, the view requires the model to implement the Searchable interface . The result of
this is that the view is only usable by certain models. But what about other views which may
need other data sets from the same model?. What if a model doesnt implement Searchable.
The issue is one of Separation of Concerns. Should the model know how it is going to be used?
No. The model should be dictating how it is used and the system should accommodate it.
Should arbitrary models model be modified to implement the Searchable interface? Ideally the
model should be reusable without modification. Otherwise each model which can used be the
view needs to be modified.
The problem arises because each view requires models to implement specific interfaces. In the
real world, a model is going to be used by any number of views. The model should not be modified in order to allow each potential view to use it. It causes clutter in the model and causes
harm by meaning the model cannot easily be reused by the same view in two different ways.
The cause of confusion is the term Model. When people refer to Models they generally mean
Domain models. That is, the model which encompasses the problem domain, dealing with
real-world concepts. Blogs, users, products, etc. In MVC, while the Model does contain these
things, the domain model is not the Model referred to in MVC.
Is the following code the solution?
PHP Code
class ListView
{
private $model;
private $template;
public $filter;
public function __construct(Searchable $model, Template $template)
{
$this->model = $model;
$this->template = $template;
}
public function output()
{
$this->template->assign(data, $this->model->getData($filter));
return $template->output();
}
}
//controller code
Chapter - 04
Page - 33
Rz Rasel
Chapter - 04
Page - 34
Rz Rasel
Chapter - 04
Page - 35
Rz Rasel
Chapter - 04
Page - 36
Rz Rasel
Chapter - 04
Page - 37
Rz Rasel
Chapter - 04
Page - 38
Rz Rasel
Chapter - 04
Page - 39
Rz Rasel
}
public function output()
{
$perPage = $this->model->getRecordsPerPage();
$pageNo = $this->model->getCurrentPage();
if(empty($pageNo) || !is_numeric($pageNo) || $pageNo < 1) $pageNo = 1;
$result = $this->viewModel->find($perPage, ($pageNo-1)*$perPage);
$totalRecords = $this->model->getTotalResults();
$totalPages = ceil($totalRecords/$perPage);
for($i = 1; $i <= $totalPages; $i++)
$this->template->appendSection(page, array(num => $i, class => $i ==
$pageNo ? $this->currentClass : ));
foreach($result as $record)
$this->template->appendSection(record, $record);
return $this->template->output();
}
}
The PaginationView uses any ViewModel which implements Pageable. The way the template
system works is irrelevant. It is included for demonstration purposes only. The ViewModel is
then defined in order to supply the view with the data it needs:
PHP Code
class PagedUserListViewModel implements Pageable, Searchable
{
private $searchName;
private $model;
private $page = 1;
public function __construct(UserModel $model)
{
$this->model = $model;
}
public function setCriteria($criteria)
{
$this->searchName = $name;
}
public function find($limit, $offset)
{
return $this->user->findByName($this->searchName, $limit, $offset);
}
public function getRecordsPerPage()
{
//Lets show 20 users per page.
return 20;
}
public function getCurrentPage()
{
return $this->page;
}
public function getTotalResults()
{
Chapter - 04
Page - 40
Rz Rasel
}
public function setPage($page)
{
$this->page = $page;
}
Of course the same could be done with a different model: Blogs, products, etc. The controller
is simple, too:
PHP Code
class PagedUserListController
{
private $viewModel;
public function __construct(PagedUserListViewModel $viewModel)
{
$this->viewModel = $viewModel;
}
public function search($criteria)
{
$this->viewModel->setCritera($criteria);
}
public function setPage($page)
{
if(is_numeric($page))
{
$this->viewModel->setPage($page);
}
}
}
By separating everything out, any piece of the view layer can be substituted. The way the view
interacts with the model is not affected by either changes to the view or changes to the model.
If there are two different user lists with different requirements (e.g. different search criteria)
only the View Helper needs to be changed. The view and the template would remain the same.
The view is reusable for any model by supplying it with a different ViewModel:
Conclusion
This is, of course, noting but a single implementation of the idea, however, it demonstrates
the benefits of separating the view elements well and should provide a solid base for anyone
wishing to develop the idea further. This is of course, all open to criticism. There is plenty of
room for improvement and some of the minor implementation details included here may not
be done in the best way (Should the variables being replaced in the template be put in the
helper instead of the view). However, using practical examples, I believe Ive successfully
argued the case for splitting views into 3 parts. It is more code to set up, but the power and
reusability achieved by doing this makes it more than worthwhile.
A small disclaimer
All the code presented in this article is for information only, It uses things such as $_POST,
Chapter - 04
Page - 41
Rz Rasel
Chapter - 04
Page - 42
Rz Rasel
ontents
05
44
44
44
44
44
45
45
45
46
46
47
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 05
Page - 43
Rz Rasel
Chapter - 05
Page - 44
Rz Rasel
Chapter - 05
Page - 45
Rz Rasel
}
?>
$this->model = $model;
}
public function invoke()
{
if(!isset($_GET[book]))
{
return $this->model->getBookList();
}
else
{
return $this->model->getBook($_GET[book]);
}
}
public function output()
{
return<h1> . $this->model->text . </h1>;
}
In the above code snippet of PHP MVC framework example, the controller class instantiates
the model using its constructor. Different methods of model are called based on the request
nature. When the page is loaded for the first time, a getBookList method of model is called
to return all book details and getBook is called when a GET request is made, which results in
a specific book detail based on the requested book name. The output function of a controller
is called to get the application name saved in text property of model class.
View in PHP MVC Framework
In PHP MVC framework, the view is responsible for all the display logic used to present data
from the model to the user. It passes the user input to a controller using control events. In
short, a view is a part of application that involves the generation of the html and interaction
with user.
In the example of Book Selection, the view presents data to a user with a combo-box and a
submit button. It instantiates the Model and Controller classes to call the invoke method
of a controller and populates the combo-box with the retrieved data.
Code snippet
<?php
$model = new Model ();
$controller = new Controller ($model);
echo $controller->output ();
$books= $controller->invoke ();
if($_SERVER[REQUEST_METHOD] === GET)
{
if(isset ($_GET[book]))
{
echo You selected . $books->name . version: . $books->version .
Year of published: . $books->yearOfPublish ;
exit;
}
}
Chapter - 05
Page - 46
Rz Rasel
}
?>
<?php
class Model
{
public $text;
public function __construct()
{
$this->text = Book Selection;
}
public function getBookList()
{
Chapter - 05
Page - 47
Rz Rasel
}
?>
}
public function getBook($name)
{
$allBooks = $this->getBookList();
return $allBooks [$name];
}
<?php
class Controller
{
private $model;
public function __construct(Model $model)
{
$this->model = $model;
}
public function invoke()
{
if(!isset($_GET[book]))
{
return $this->model->getBookList();
}
else
{
return $this->model->getBook($_GET[book]);
}
}
public function output()
{
return<h1> . $this->model->text . </h1>;
}
}
?>
<?php
$model = new Model ();
$controller = new Controller ($model);
echo $controller->output ();
$books= $controller->invoke ();
if($_SERVER[REQUEST_METHOD] === GET)
{
if(isset ($_GET[book]))
{
echo You selected . $books->name . version: . $books->version .
Year of published: . $books->yearOfPublish ;
exit;
Chapter - 05
Page - 48
Rz Rasel
Chapter - 05
Page - 49
Rz Rasel
ontents
06
51
51
52
52
52
52
53
54
55
56
56
57
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 06
Page - 50
Rz Rasel
Model
View
Controller
The application is divided into these three main components, each one in charge of different
tasks.
Chapter - 06
Page - 51
Rz Rasel
Chapter - 06
Page - 52
Rz Rasel
MODEL
USER
1
7
CONTROLLER
VIEW
The controller (books_controller.php) receives the user request as an HTTP GET or POST request (we can also have a central controller, for example index.php receiving it and then calling books_controller.php).
The controller examines the request and the parameters and calls the model (book_model.
php) asking him to return the list of available fantasy books.
The model is responsible for getting that information from the database (or wherever it is
stored), apply filters or logic if necessary, and return the data representing the list of books.
The controller will use the appropriate view to present these data to the user. If the request
came from a mobile phone, a view for mobile phones will be used, if the user has a particular
skin selected, the corresponding view will be chosen, and so on.
What are the Advantages?
The most obvious advantage we gain using MVC is a clear separation of presentation (the
interface with the user) and application logic.
Support for different types of users using different types of devices is a common problem these
days. The interface presented must be different if the request came from a desktop computer
or from a cell phone. The model returns exactly the same data, the only difference is that the
controller will choose a different view to render them (we can think of a different template).
Chapter - 06
Page - 53
Rz Rasel
app/
cake/
vendors/
The app folder is where you place your files. It is your place to develop your part of the application.
The cake folder is where cakePHP has its files and where they have developed their part (main
framework functionality).
The vendors folder is for third-party PHP libraries if needed.
Your working place (app directory) has the following structure:
app/
config/
controllers/
locale/
models/
plugins/
tests/
tmp/
vendors/
views/
webroot/
Now you have to put your controllers in the controllers directory, your models in the models
directory and your views in the views directory!
Once you get used to your framework, youll be able to know where to look for almost any
piece of code you need to modify or create. This organization alone makes maintainability a
lot easier.
Lets Framework our Example
Since this tutorial is not intended to show you how to create an application using cakePHP,
well use it only to show example code for the model, view and controller components and
comment on the benefits of using an MVC framework. The code is oversimplified and not suitable for real applications.
Chapter - 06
Page - 54
Rz Rasel
Chapter - 06
Page - 55
Rz Rasel
Chapter - 06
Page - 56
Rz Rasel
Chapter - 06
Page - 57
Rz Rasel
ontents
07
59
61
61
62
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 07
Page - 58
Rz Rasel
Chapter - 07
Page - 59
Rz Rasel
Chapter - 07
Page - 60
Rz Rasel
Chapter - 07
Page - 61
Rz Rasel
Chapter - 07
Page - 62
Rz Rasel
ontents
08
64
64
65
66
66
67
69
69
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 08
Page - 63
Rz Rasel
Chapter - 08
Page - 64
Rz Rasel
MODEL
UPDATES
MANIPULATES
VIEW
CONTROLLER
SE
ES
SE
USER
The image shows the single flow layout of data, how its passed between each component, and
finally how the relationship between each component works.
Model
The Model is the name given to the permanent storage of the data used in the overall design.
It must allow access for the data to be viewed, or collected and written to, and is the bridge
between the View component and the Controller component in the overall pattern.
One important aspect of the Model is that its technically blind by this I mean the model
has no connection or knowledge of what happens to the data when it is passed to the View
or Controller components. It neither calls nor seeks a response from the other parts; its sole
purpose is to process data into its permanent storage or seek and prepare data to be passed
along to the other parts.
The Model, however, cannot simply be summed up as a database, or a gateway to another
Chapter - 08
Page - 65
Rz Rasel
Its important to remember the Controller is only given tasks to perform when the user interacts with the View first, and that each Controller function is a trigger, set off by the users
interaction with the View. The most common mistake made by developers is confusing the
Controller for a gateway, and ultimately assigning it functions and responsibilities that the
View should have (this is normally a result of the same developer confusing the View component simply as a template). Additionally, its a common mistake to give the Controller func-
Chapter - 08
Page - 66
Rz Rasel
Chapter - 08
Page - 67
Rz Rasel
Chapter - 08
Page - 68
Rz Rasel
Chapter - 08
Page - 69
Rz Rasel
Chapter - 08
Page - 70
Rz Rasel
ontents
09
72
72
72
72
73
73
73
73
74
74
74
74
75
75
75
76
76
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 09
Page - 71
Rz Rasel
Chapter - 09
Page - 72
Rz Rasel
Chapter - 09
Page - 73
Rz Rasel
Chapter - 09
Page - 74
Rz Rasel
Chapter - 09
Page - 75
Rz Rasel
Chapter - 09
Page - 76
Rz Rasel
Chapter - 09
Page - 77
Rz Rasel
Chapter - 09
Page - 78
Rz Rasel
ontents
10
80
81
82
83
84
84
85
rzandapp@gmail.com
Feel Free To Ask Question You May Have
Chapter - 10
Page - 79
Rz Rasel
Client
http Request
http Response
Controllr
Model
View
Chapter - 10
Page - 80
Rz Rasel
Rz Rasel
else
{
// show the requested book
$book = $this->model->getBook($_GET[book]);
include view/viewbook.php;
}
In the following MVC Sequence Diagram you can observe the flow during a http request:
USER
CONTROLLER
MODEL
VIEW
http Request
request Data
return Data
formate Output
Chapter - 10
Page - 82
Rz Rasel
View (Presentation)
The view(presentation layer)is responsible for formating the data received from the model in
a form accessible to the user. The data can come in different formats from the model: simple
objects( sometimes called Value Objects), xml structures, json,
The view should not be confused to the template mechanism sometimes they work in the
same manner and address similar issues. Both will reduce the dependency of the presentation layer of from rest of the system and separates the presentation elements(html) from the
code. The controller delegates the data from the model to a specific view element, usually
associated to the main entity in the model. For example the operation display account will
be associated to a display account view. The view layer can use a template system to render
the html pages. The template mechanism can reuse specific parts of the page: header, menus,
footer, lists and tables, . Speaking in the context of the MVC pattern
Chapter - 10
Page - 83
Rz Rasel
the Model and View are separated, making the application more flexible.
the Model and view can be changed separately, or replaced. For example a web appli-
Chapter - 10
Page - 84
Rz Rasel
Chapter - 10
Page - 85
Rz Rasel
}
?>
Chapter - 10
Page - 86
Rz Rasel
Chapter - 10
Page - 87
Rz Rasel