Sei sulla pagina 1di 87

Dinner Time Hand Note

PHP
Model View Controller

Rz Rasel

Model View Controller (PHP)

Dinner Time Hand Note


PHP Model View Controller
Rz Rasel

Rz Rasel

Model View Controller (PHP)

Dinner Time Hand Note


PHP Model View Controller
DESIGN AND DEVELOPMENT

1st Edition

Rz Rasel

Rz Rasel

Model View Controller (PHP)

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

1st Edition: August 2014

Cover Illustration Copyright by Rz Rasel (rzandapp@gmail.com)


Cover design by Rz Rasel.
Book design by Rz Rasel
Editing by Rz Rasel
Chapter opening illustrations Rz Rasel

Rz Rasel

Model View Controller (PHP)

REDITS

I would like to thanks all of them.


Author
Rz Rasel

Others
Callum Hopkins

Rz Rasel (Rashed - Uz - Zaman) is a Software Engineer. Back-end


and Front-end developer web experience. Also working in PHP,
Android, Database like Sql, MySql, Sqlite. Web developer, Web
designer, and blogger. Contact e-mail:- rzandapp@gmail.com.
Callum Hopkins is a designer and front-end developer web experience and a Bachelors degree in Design for Digital Media. With
knowledge in both design and development, he is able to influence both sides of the web building process.

Kasia Mikoluk

Kasia Mikoluk is a web developer.

Tom Butler

Tom Butler work as a Web Developer (Specialising mainly in PHP)


for a web design agency. Also a part time lecturer. Tom Butler
have an interest in programming since messing around with the
code for various computer games since he was about twelve. He
consider it an art more than a science and love to explore the creative side more than the functional side of the subject.

Pablo Pastor

Pablo Pastor is a web developer.

I would like to thanks all of them.

Rz Rasel

Model View Controller (PHP)

bout author

Rz Rasel (Rashed - Uz - Zaman) Software Engineer. Software developer, Software designer,


System designer, Database designer, Web developer, Web designer, and blogger born in Bangladesh, and now living in Bangladesh.

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

Model View Controller (PHP)

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

Model View Controller (PHP)

et In Touch

Get in touch with writer


WordPress Blog:- https://arzrasel.wordpress.com
Facebook:-
https://www.facebook.com/rzprogramming
Facebook:-
https://www.facebook.com/groups/merzrasel/
Facebook:-
https://www.facebook.com/groups/rzprogrammer/
E-mail:- rzandapp@gmail.com

Rz Rasel

Rz Rasel

Model View Controller (PHP)

ontents

01
02
03

MVC Architecture
MVC Basic Architecture. . . . . . . . . . . . . . . . . . . . . . .
The model. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The controller . . . . . . . . . . . . . . . . . . . . . . . . . . .

15
15
15
16

Understanding Model View Controller


Understanding the Model View Controller (MVC) . . . . . . . . . . .
A Brief History of Model View Controller (MVC). . . . . . . . . . . .
So What Exactly is a Model View Controller?. . . . . . . . . . . . .
MVC in PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . .

18
18
18
19

The View gets its own data from the Model


Abstract. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MVC - Model View Confusion . . . . . . . . . . . . . . . . . . . .
The view is more than a template. . . . . . . . . . . . . . . . . .
Example 1 PHP Code. . . . . . . . . . . . . . . . . . . . . . . .
Example 2 PHP Code. . . . . . . . . . . . . . . . . . . . . . . .
Binding logic is problematic. . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
When the view really needs the model . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Better reusability . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23
23
23
24
24
24
24
25
25
25
26
26
27
27
28
28
29
29
30

Rz Rasel

Model View Controller (PHP)

ontents

04

05

MVC models are not domain models


Flexibility vs Reusability . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terminology: ViewModels View Helpers, Models . . . . . . . . . . . .
What is a view helper?. . . . . . . . . . . . . . . . . . . . . . .
An Implementation . . . . . . . . . . . . . . . . . . . . . . . . .
The Template. . . . . . . . . . . . . . . . . . . . . . . . . . . .
The View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The ViewModel . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A small disclaimer . . . . . . . . . . . . . . . . . . . . . . . . .

32
32
33
34
34
35
35
35
35
35
36
36
36
37
37
38
39
39
40
41
41
41

PHP MVC Framework Basic Introduction


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . .
What is PHP MVC Framework? . . . . . . . . . . . . . . . . . . . .
How to implement PHP MVC Framework? . . . . . . . . . . . . . . .
Model in PHP MVC Framework . . . . . . . . . . . . . . . . . . . .
Code snippet (Book Class) . . . . . . . . . . . . . . . . . . . . .
Code snippet (Model Class). . . . . . . . . . . . . . . . . . . . .
Controller in PHP MVC Framework. . . . . . . . . . . . . . . . . .
Code snippet (controller class) . . . . . . . . . . . . . . . . . . .
View in PHP MVC Framework . . . . . . . . . . . . . . . . . . . .

44
44
44
44
44
45
45
45
46

Rz Rasel

Model View Controller (PHP)

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

PHP MVC Pattern and Routing URLs


Routing and URLs. . . . . . . . . . . . . . . . . . . . . . . . . .
DRY (Dont Repeat Yourself) & Templates . . . . . . . . . . . . . .
Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

59
61
61
62

MVC Pattern and PHP


PHP MVC Pattern. . . . . . . . . . . . . . . . . . . . . . . . . .
Understanding MVC . . . . . . . . . . . . . . . . . . . . . . . . .
Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MVC in PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . .

64
64
65
66
66
67
69
69

Rz Rasel

Model View Controller (PHP)

ontents

09

10

MVC in PHP Real world program


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Converting currencies - The Model . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Enabling user input - The Controller. . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . .

72
72
72
72
73
73
73
73
74
74
74
74
75
75
75
76
76

PHP Model View Controller


PHP Model View Controller . . . . . . . . . . . . . . . . . . . . .
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model and Entity Classes. . . . . . . . . . . . . . . . . . . . . .
View (Presentation) . . . . . . . . . . . . . . . . . . . . . . . . .
viewbook.php . . . . . . . . . . . . . . . . . . . . . . . . . . .
booklist.php. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . .

80
81
82
83
84
84
85

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Rz Rasel

Model View Controller (PHP)

Rz Rasel

Model View Controller (PHP)

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

Model View Controller (PHP)


MVC Basic Architecture
Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three
parts:
Model - The lowest level of the pattern which is responsible for maintaining data.
View - This is responsible for displaying all or a portion of the data to the user.
Controller - Software Code that controls the interactions between the Model and View.
MVC is popular as it isolates the application logic from the user interface layer and supports
separation of concerns. Here the Controller receives all requests for the application and then
works with the Model to prepare any data needed by the View. The View then uses the data
prepared by the to generate a final presentable response. The MVC abstraction can be graphically represented as follows.

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

Model View Controller (PHP)


data. They are script based templating systems like JSP, ASP, PHP and very easy to integrate
with AJAX technology.
The controller
The controller is responsible for responding to user input and perform interactions on the data
model objects. The controller receives the input, it validates the input and then performs the
business operation that modifies the state of the data model.
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 - 01
Page - 16

Rz Rasel

Model View Controller (PHP)

ontents

02

Understanding Model View Controller


Understanding the Model View Controller (MVC) . . . . . . . . . . .
A Brief History of Model View Controller (MVC). . . . . . . . . . . .
So What Exactly is a Model View Controller?. . . . . . . . . . . . .
MVC in PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . .

18
18
18
19

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Chapter - 02
Page - 17

Rz Rasel

Model View Controller (PHP)


Understanding the Model View Controller (MVC)
As a computer science student, one of the first things youll learn is the model-view-controller, or MVC. MVC is a widely used software architecture pattern that informs the design of
some of your favorite software applications. Now well take a look at the MVC pattern in some
more detail, especially how it is used in PHP.
If youd rather just dive in and start creating your own apps, consider this course on PHP.
A Brief History of Model View Controller (MVC)
Lets go all the way back to the 70s. Man has been to the moon, the civil rights movement
has been a huge success, and the counterculture revolution is in full swing. More importantly
for us, computer science has now established itself as a legitimate field, not just the eccentric
hobby of people with huge glasses and bigger beards. Some of the brightest minds in engineering and mathematics are collaborating in research labs at Stanford, Berkeley and the
dozens of private companies like Xerox and HP in what would later become Silicon Valley.
Its against this backdrop that a bunch of very talented programmers have gathered at the
Learning Research Group (LRG) of Xerox PARC in Palo Alto, California (the current home of
Apple). These programmers are Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, and Scott
Wallace, among others. Together, they help create a programming language they call Smalltalk. Its already been a few years since the development of the C language at Bell Labs; there
are already some software design standards in place. However, the invention of the Smalltalk
programming language would affect virtually all these standards, and set the tone for the future of programming.
It was from this language that the Model-View-Controller pattern first emerged. Ted Kaehler is
usually given credit for its development in 1978 in a paper titled A note on DynaBook requirements, though his first name for it was Thing-Model-View-Set. The aim of this MVC pattern
was to bring the user closer to the digital model that existed inside the computer program.
In Kaehlers own words, the user was czar, and the MVC helped mediate the way the user
could interact with a software program.
If that sounds too abstract to you, dont worry youll have a firm understanding of MVC by
the time were done.
What you should know for now is that MVC described the way a user could interact with a computer program. This would later go on to inform Graphical User Interfaces (GUIs), and thus,
by proxy, pretty much all of computer science. If it wasnt for Kaehler and his MVC pattern,
you might still be typing commands into a terminal right now.
So What Exactly is a Model View Controller?
A Model-View-Controller is a pattern of software architecture. It controls how different applications interact with a user.
This web page is a perfect example of the MVC structure. Here, the HTML structure of this
web page is the model, the CSS stylesheets that control its appearance are the View, and the
browser that you use to interact with the web page is the controller.
Model: The model is a representation of knowledge. That is, the model contains the actual
data that has to be shown to the user. All data is held in a structured format. For example,
the HTML on this web page holds the actual text that you see inside structured HTML <tags>.
View: The view is a visual representation of the model. The view informs the way data strucChapter - 02
Page - 18

Rz Rasel

Model View Controller (PHP)


tured in the model will be made visible to the user. For example, the HTML may hold the
text, but the colors, font size and font style information is actually held by independent CSS
stylesheets i.e. the view.
Controller: A controller is the environment that bridges the divide between the user and the
system. This is the device that lets the user interact with the system. In the above examples,
the browser is the controller that helps you interact with the web page.
One way of representing this is as follows:

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

Model View Controller (PHP)


..
Config
Console
Controller
Lib
Locale
Model
Plugin
Test
Tmp
Vendor
View
Webroot
.htaccess
index.php
Here, the model, view and controller are included in separate folders. This is what
/view/ contains:

..
Elements
Emails
Errors
Helper
Layouts
Pages
Scaffolds
/Model/:

..
Behavior
Datasource
AppModel.php
And /Controller/:

Chapter - 02
Page - 20

Rz Rasel

Model View Controller (PHP)


..
Component
AppController.php
PagesController.php
Heres the MVC in CodeIgniter, another very popular PHP framework:

..
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

Model View Controller (PHP)

ontents

03

The View gets its own data from the Model


Abstract. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MVC - Model View Confusion . . . . . . . . . . . . . . . . . . . .
The view is more than a template. . . . . . . . . . . . . . . . . .
Example 1 PHP Code. . . . . . . . . . . . . . . . . . . . . . . .
Example 2 PHP Code. . . . . . . . . . . . . . . . . . . . . . . .
Binding logic is problematic. . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
When the view really needs the model . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Better reusability . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

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

Model View Controller (PHP)


Abstract
MVC is a common subject in the PHP community at the moment. There are a large body of
articles, tutorials and code examples on the subject. Most of which deviate from the traditional
approach to MVC and subscribe to an approach closer to MVP. Very few of these follow the
MVC standard of allowing the view access to the model. Yet this is what they ascribe to be.
This article explains why the view should have access to the model and the problems which
are created by taking the differing approach commonly used throughout the PHP community.
MVC - Model View Confusion
MVC is a very common architecture in PHP these days. Everyone seems to be writing their own
MVC framework. Its a great learning exercise. The problem however, is the information which
is available to PHP developers. Much of it is poorly written, a great deal is fairly old fashioned
and teaches bad practices. The majority of MVC related articles go off on tangents about such
topics as the merits of DataMapper vs ActiveRecord, template systems, directory structures,
how to do form processing and validation and other irrelevant implementation details. The biggest problem, however, is that despite the inclusion of all this unrelated information they still
almost all get the basics wrong.
In MVC the view should access the model directly. This something which I have to argue a lot
and its one of the most overlooked facts about the architecture.
It is important to note that in order to correctly apply the MVC architecture, there must be
no interaction between models and views: all the logic is handled by controllers.
This is wrong. It specifies this nowhere in MVC. In fact, it states the exact opposite. Lets take
a step back and take a look at some explanations of MVC from outside the PHP world.
As a starting point, the wikipedia article on MVC states:
A view queries the model in order to generate an appropriate user interface (for example,
the view lists the shopping carts contents). The view gets its own data from the model. The
controller may (in some implementations) issue a general instruction to the view to render
itself. In others, the view is automatically notified by the model of changes in state (Observer) which require a screen update.
Of course wikipedia is not a credible source so heres some more academic explanations:
The views know of the model and will interact with the model.
The view is more than a template
The catalyst for this error appears to be the idea that a view is a template. It contains the
HTML, perhaps a few processing instructions for looping through arrays but they state that it
gets passed its variables from the controller.
The result of this self-imposed restriction makes putting any logic at all in the MVCs view
seem wrong, harking back to the days of mixing HTML and PHP. Dont get me wrong Im not
going to argue that mixing HTML and PHP is a good thing. Templates serve a valuable purpose.
They just dont constitute a view in MVC.
Of course, when the model is incorrect or even non-existent and the controller is doing the
models job it presents yet another hurdle. When the controller is doing the job of a model

Chapter - 03
Page - 23

Rz Rasel

Model View Controller (PHP)


anyway, as in most PHP MVC frameworks, there is no model for the view to access! This has
to be done by the controller.
Because of these fundamental problems, the only solution is to make the controller act as a
mediator. Generally by querying the model and passing the result to the view.
Example 1 PHP Code
$user = $this->model->user->findById($id);
$this->template->assign(firstname, $user[firstName]);
$this->template->assign(surname, $user[surname]);
$this->template->assign(address1, $user[address1]);
or pass a simple key-value array which has been retrieved from the model (which is just a data
access layer) to the template:
Example 2 PHP Code
$user = $this->model->user->findById($id);
$this->template->assign(user, $user);
While the latter is certainly an improvement, it merely makes the problem slightly less noticeable: binding logic.
This puts extra work into the controller: Binding variables to the template. Controllers are not
designed to be reused. By putting this logic here the reusability has instantly been reduced.
There are bigger issues than that though.
Binding logic is problematic
By including this binding logic, a large number of potential issues have been created in terms
of reusability and maintainability. Views are intended to be reused. In the examples above
Im showing some basic user information. The template here may well (and, because the template is separated, can) be reused. This is a good thing and certainly something to strive for.
However, when the binding logic is introduced, much of this reusability is lost.
The first problem, then, is repeated code. The binding logic needs to be written in each and
every controller which uses the view. This will do nothing but slow down development.
There is a potential for inconsistent naming. For example, this is possible:
PHP Code
$this->template->assign(lastname, $user[surname]));
This is something easily dismissed as I wouldnt do that however, when working with a team,
its easy for things like this to slip in unnoticed and cause bugs which are difficult to track
down.
What if there are two users being represented in the view? Both of them have surnames and
firstnames. The view now needs to reference firstname1 and firstname2 How can this be
kept consistent across controllers and views? It cant. This all causes confusion for anyone
else looking at the code. Isnt it better to prevent this in the first place?

Chapter - 03
Page - 24

Rz Rasel

Model View Controller (PHP)


In a similar vein, its possible for the controllers to be inconsistent. Because this logic even
exists, it removes any contract between the view and the model. This means address1 in the
view doesnt really represent anything. It can be anything. Theres nothing to stop the controller sending the wrong data.
For example, in one job I worked on a site with a similar set up. The requirements changed
along the lines of can you remove the address from this page rather than modify the view
one of my colleagues decided it would be a good idea to change the controller to do $template>assign(address, null); Of course when the view was reused elsewhere by another developer, he had to spend time working out why the address was showing on the new page and
not on the old one. The controller now inadvertently contained display logic: it was telling the
view not to show the address. Again, prevention here is better than cure.
Performance should be the final consideration. The binding logic creates more code. Although
code cleanliness/reusability/maintainability shouldnt be sacrificed for performance, in this
case worse performance is a result of worse code.
When the view really needs the model
The above examples are trivial. As with most trivial examples, the bigger problems dont become apparent until the scale and complexity are increased. A better example is pagination.
A pagination controller may look like this:
PHP Code
$perPage = 10;
$page = $_GET[page];
$users = $this->model->user->find($perPage, $perPage * $page);
$totalPages = $this->user->count() / $perPage; $this->view->assign(users, $users);
$this->view->assign(totalPages, $totalPages);
$this->view->assign(page, $page);
Here is basic logic behind pagination in the controller. The big problem here is that none of this
code is reusable. Even though it will be the same for any paginated data. The only thing that
will change is the current page and number of records to show per page.
Just because the controller is calling a function on the model doesnt mean the display and
business logic have been moved out of the controller.
How else could this be done? A better solution would be to set the state in the model and have
the view read it. This way the view is agnostic about the state of the model (which page its
on) and all the pagination logic is contained (and reusable) within the view.
PHP Code
$this->model->setPage($_GET[page]);
This should be the entirity of the controller code.
This way, all the pagination logic: working out the total number of pages, working out the
limit/offset (Details which are only relevant to how the data is going to be displayed when its
paginated) can be moved to the view. The view will call $user->find() and $user->count()
with the relevant parameters. The controller is doing less and the view is doing more. This

Chapter - 03
Page - 25

Rz Rasel

Model View Controller (PHP)


inevitably leads to higher reusability.
It could be argued that the view should contain its own state: Which page its on. However,
the reason that the model holds the state and not the view is that the model can be in use by
multiple views. It may be useful for multiple views to use the same data. For example, having
a second view which used the paginated data and created some aggregated statistics about
the data displayed on the current page. This would need to be in sync with the first view and
always use the same data set. By storing the state in the model rather than the view, the page
can be changed and both views will reflect the changes. This reduces repeated code and adds
flexibility while improving separation of concerns.
The View always has a contract with a model. Whether its a primitive array or a complex object, the view requires specific information. This is naturally unavoidable. By using the Model
directly, this contract is immediately fulfilled. If primitives are passed to the view, it has no
way of knowing whether this contract is fulfilled until it breaks. Even if the result is a set of
objects, the view cannot know whether the set is correct (because its likely a primitive array
containing objects) until it tries to use an object. By using the Model, the view can check this
contract is fulfilled as the model is assigned to it, preferrably in its constructor.
Even ignoring this, and assuming your controller always passes a valid data set you still lose
re-usability. The biggest issue with the controller as a mediator approach is that all the
data fetching logic (the calls to the model) has to be done in every single controller using the
view, causing repeated code and therefore reduced reusability. In the pagination example, all
the calculations need to be repeated in each controller that uses the view. As an application
developer, each time you want to use pagination, would you rather pass a single variable to
the model which sets the page and does everything for you or fetch the records, work out the
total number of pages then pass the result to the view?
And pagination is a trivial example. In the real world, that controller logic is liable to change.
If its repeated, it needs to be updated in every controller. By creating the reusability and
separation of concerns suggested by MVC the code doesnt need repeated and changes to the
model will automatically be reflected in any view without changes to the code. This is a result
of the reduction of binding logic and therefore increasing reusability.
The idea here (and the one suggested by MVC in general) is putting all the business logic
in the model and all the display logic in the view. All the controller should be doing is
getting these talking. The less the controller is doing the better. Less controller code means
more reusable code.
Better reusability
With all this theorising, it would certainly be worthwhile to include a basic real world example
of why views are more than templates. I believe templates are worthwhile but they do not
constitute a View. Much in the same way the model layer is more than data access, the view
is more than a template.
To demonstrate, heres a simple scenario: Show a list of users which can be filtered by searching for their name.
Some example controller code. This will now be as minimal as possible.
PHP Code
class UserListController

Chapter - 03
Page - 26

Rz Rasel

Model View Controller (PHP)


{

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

Model View Controller (PHP)


{

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

Model View Controller (PHP)


public function setCriteria($criteria)
{
$this->searchName = $criteria;
}
public function getData()
{
//Find the selected users.
return $this->db->query(SELECT * FROM users WHERE name like :name,
array(:name, $this->searchName);
}
}
class BlogModel implements Listable, Searchable
{
private $searchTitle;
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
public function setCriteria($criteria)
{
$this->searchTitle = $title;
}
public function getData()
{
//Find the selected blogs.
return $this->db->query(SELECT * FROM blogs WHERE title like :title,
array(:title, $this->searchTitle);
}
}
The controller code looks like this:
PHP Code
class SearchController
{
private $model;
public function __construct(Searchable $model)
{

$this->model = $model;
}
public function search($criteria)
{

$this->model->setCritera($criteria);
}
}
Notice that its not tied to any specific model. Because of the very strict separation of concerns
which is achieved by the view getting its own data from the model rather than being fed it by
the controller, the controller code is reusable. And so is the view:
PHP Code

Chapter - 03
Page - 29

Rz Rasel

Model View Controller (PHP)


class ListView
{
private $model;
private $template;
public function __construct(Listable $model, Template $template)
{
$this->model = $model;
$this->template = $template;
}
public function output()
{
$this->template->assign(data, $this->model->getData());
return $template->output();
}
}
Again, its not tied to a specific model. The view does not care where its data comes from or
what the data is. But theres more. Any of the three components can be substititued and reused. The controller can be changed where needed. The view can be substituted for one which
doesnt use a template engine while reusing the controller and model. Another controller can
be added to the system which uses $_POST and it can use the exact same model and view.
By enforcing the separation of concerns that MVC dictates, the real power of it shines through.
Conclusion
My main goal here is to show that just because an idea is widespread does not mean it is
correct or best practice. Not everything you read is entirely accurate. Without valid reasoning, a programming practice, regardless of its popularity is not always a good practice. Take
singletons as a perfect example. Something many articles seem to miss. They tell you how
but not why.
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 - 03
Page - 30

Rz Rasel

Model View Controller (PHP)

ontents

04

MVC models are not domain models


Flexibility vs Reusability . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terminology: ViewModels View Helpers, Models . . . . . . . . . . . .
What is a view helper?. . . . . . . . . . . . . . . . . . . . . . .
An Implementation . . . . . . . . . . . . . . . . . . . . . . . . .
The Template. . . . . . . . . . . . . . . . . . . . . . . . . . . .
The View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The ViewModel . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A small disclaimer . . . . . . . . . . . . . . . . . . . . . . . . .

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

Model View Controller (PHP)


Flexibility vs Reusability
To completely contradict part, while correct, its not the solution either. It is certainly an improvement over fat controllers. However, was it much of an improvement? Isnt reusability
reduced by giving the view access to the model?
In any software design, there is always a trade off between flexibility and reusability. On one
hand a very flexible system could be created where the client code has to specify pretty much
everything. For example, in terms of views, passing a model object to the template and have
the template do everything: query the model, process the data and generate the HTML. This
is incredibly flexible: there are no limitations on what it can do. However, its not reusable at
all. The template is tightly bound to the individual model and the logic is contained within it.
To make an even slightly different version everything would need to be re-coded.
On the other hand, a lot of assumptions could be made about the nature of the model in the
system the view, with minimal to no configuration could take any model which meets these
assumptions. Of course things break when requirements change or it needs to do something
even slightly different. It encourages a copy, paste and modify slightly mentality, which is of
course, not a good idea.
Finding the balance is the key. It will always differ based on the requirements of the software,
how large the project is, whether its going to change often and whether its likely to grow
beyond its initial scope.
The last point here is a hard one to judge. Would it be worthwhile to deploy a template engine
or full MVC stack for a 5 page brochure site? how about 10 page? What if that 5 page site grew
into a 30 page site within a year then the client wanted latest news added to each page. If the
system was built on a template engine or CMS to begin with it would be easier.
But is this the right answer? Should developers deploy a full MVC stack just to write to a log
file? Trying to be a soothsayer and second guess what clients (who are notoriously fickle beings) will ask for in a year isnt the solution. However, spending a little extra time at the start
of a project ensuring further developments are as simple as possible will undoubtedly make
things easier in the long run.
It argues that in MVC the view should have direct access to the model. It contains some basic
code examples to demonstrate the benefits. The solution is for demonstration only. As such it
is neither complete, nor perfect. However, the general idea of the view calling functions on the
model directly presents some new problems.
Problems created by the view accessing the model
The biggest problem is also one of its biggest strengths: it creates a firm contract between
the model and the view. This reduces reusability of the view because the model now needs to
have a very specific interface.
Reusable ListView class:
PHP Code
class ListView
{
private $model;
private $template;

Chapter - 04
Page - 32

Rz Rasel

Model View Controller (PHP)

public function __construct(Searchable $model, Template $template)


{
$this->model = $model;
$this->template = $template;
}
public function output()
{
$this->template->assign(data, $this->model->getData());
return $template->output();
}

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

Model View Controller (PHP)


$this->view->filter = firstname = . $name . ;
Here, the state has been moved into the view. The view contains the search criteria rather
than the model. Is this the answer?
No, For a start, Display logic has been reintroduced into the controller. More importantly
though, now any model which uses the view requires a very specific getData implementation. This severely reduces reusability to only models which follow this specification.
Extending this idea into more complex views means more specific calls to a model, which
means its less reusable views. To use a totally different model would be programmatically trying to put a square plug in a round hole.
Consider this: developer A develops a model and a view to work together:
PHP Code
class ModelA
{
public function getData($order, $limit, $filter)
{
//...
}
}
class ViewA
{
//...
public function output()
{
$result = $this->model->getData($this->order, $this->limit, $this->filter);
//...
}
}
Meanwhile, developer B develops a model and a view which work together:
PHP Code
class ModelB
{
public function getData($firstname)
{

//...
}
}
class ViewB
{
//...
public function output()
{

$result = $this->model->getData(foo);
//...
}
}

Chapter - 04
Page - 34

Rz Rasel

Model View Controller (PHP)


Now theres a situation where ModelB cannot be used with ViewA and ModelA cannot be used
with ViewB even though the logic in each view may be relevant to the display of both models.
One solution is to add the relevant methods to the models but this is both messy and dangerous. This potentially introduces unrelated concepts into models (e.g. ModelA may not be
anything to do with users).
Alternatively, the views could be modified, but again, theres no clean way to do it. Either they
need to extended and have the entire output() method re-written, or have some hacky logic
in the view deciding which method to call in the model.
The ideal scenario is that both the model and view can be reused without modification. This
allows for ultimate reusability and a very large amount of flexibility
The answer? Abstract the problem away.
Terminology: ViewModels View Helpers, Models
Padraic Brady wrote about this in his fantastic article The M in MVC: Why Models are Misunderstood and Unappreciated. Although he accurately points out the misunderstanding of
Models, the problem is peoples preconceptions of models. He re-enforces this by discussing
domain models in terms of MVC Models. They are not the same thing. The MVC Model does
encapsulate domain models, but for the purpose of MVC, although you can write a MVC Model
which does the job of a domain model, its impossible to use a domain model as an MVC Model.
One idea presented by Brady is to create a View Helper which contains all the interaction
between the model and the view. This is actually what MVC refers to as The model and not
a separate component. However, because the term Model has evolved to have a specific
meaning I can see why he needed to coin a fresh term for the MVCs model.
What is a view helper?
Encapsulating business logic in a helper instead of a view makes our application more modular
and facilitates component reuse. Multiple clients, such as controllers and views, may leverage
the same helper to retrieve and adapt similar model state for presentation in multiple ways.
An Implementation
The main goal is that views can be as generic (and therefore reusable) as possible, while the
ViewModel defines only how a model interacts with a specific view. This fixes the problem of
either coding a view around a model, or coding a model to fit a view. It is considered part of
the view layer, but the ViewModel can access any domain model.
The Template
This contains the HTML. This has a contract with domain models (user objects, order objects,
etc). A basic template system is used in code examples on this page for the purpsoe of demonstration. How this works is not relevant and is far beyond the scope of this article. Often
the template itself will not be reused: It is tied directly to the domain model. For example, it
knows what fields a User object has. It has direct access to its ViewModel, this allows it to
read what it needs, eliminating the need for binding logic in the view.
The View

Chapter - 04
Page - 35

Rz Rasel

Model View Controller (PHP)


This contains all the display logic for interacting with the template and is the only place the
template is interacted with directly. Most of the time it will simply assign the helper to the
template. When a View is defined it should also define an interface for the helper which it is
going to use. It does not interact with models directly. It uses a ViewModel to get any data it
needs from the model.
The ViewModel
This implements the specific interface defined alongside the view. E.g. FormView will require a
ViewModel which implements the interface FormViewModel. The ViewModels job is to link the
model layer to the view layer and store the state of the application. For instance it will store
things like sort options selected by the user and the ID of the record being edited/viewed.
This means that any part of the view layer can be substituted (and thus, the others reused).
With the same model and view, the logic in the helper could be changed. The template could
be changed.
PHP Code
class ListView
{
private $model;
private $template;
public function __construct(Searchable $model, Template $template)
{
$this->model = $model;
$this->template = $template;
}
public function output()
{
$this->template->assign(data, $this->model->getData());
return $template->output();
}
}
It requires a ViewModel as the first argument. In this case, the ViewModel must implement the
Searchable interface as before. The also controller remains identical to what it was previously:
PHP Code
class SearchController
{
private $model;
public function __construct(Searchable $model)
{

$this->model = $model;
}
public function search($criteria)
{

$this->model->setCritera($criteria);
}
}

Chapter - 04
Page - 36

Rz Rasel

Model View Controller (PHP)


The important changes happen at the model layer. The old UserModel looked like this:
PHP Code
class UserModel implements Listable, Searchable
{
private $searchName;
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
public function setCriteria($criteria)
{
$this->searchName = $name;
}
public function getData()
{
//Find the selected users.
return $this->db->query(SELECT * FROM users WHERE name like :name,
array(:name, $this->searchName);
}
}
The problem with this is that the domain model and ViewModel have been merged into one.
This violates the Single Responsibility Principle and causes domain models to contain methods which exist for the sole purpose of specific views accessing data. However this can be
resolved:
PHP Code
class UserListViewModel implements Listable, Searchable
{
private $searchName;
private $model;
public function __construct(UserModel $model)
{

$this->model = $model;
}
public function setCriteria($criteria)
{

$this->searchName = $name;
}
public function getData()
{
//Find the selected users.
return $this->model->findByName($this->searchName);
}
}
class UserModel
{
private $db;
public function __construct(Db $db)
{

Chapter - 04
Page - 37

Rz Rasel

Model View Controller (PHP)



$this->db = $db;
}
public function findByName($name)
{
//Find the selected users.
return $this->db->query(SELECT * FROM users WHERE name like :name, array(:name,
$name);
}
}
Here is a very clear distinction between a domain model and a ViewModel. This ViewModel
will always be incredibly minimalist. It will never contain complex logic, database access, its
a simple wrapper to enable view to access its data. The domain model now has a generic
findByName method which can be used by any ViewModel. The application state (what has
been searched for) remains in the ViewModel while the domain state (the data about users) is
encapsulated in the domain model.
The view layer is now made up of 3 parts. For people used to templates as views this will
likely seem daunting. However, take a look at the controller. Its entirely minimalist and reusable which is far superior to the mess of fat controllers which are required by the major
frameworks. Minimal controllers are good controllers.
To test the reusability, the view could be reused with minimal configuration by another model
with a totally different interface:
PHP Code
class ProductListViewModel implements Listable, Searchable
{
private $searchCode;
private $model;
public function __construct(ProductModel $model)
{
$this->model = $model;
}
public function setCriteria($criteria)
{
$this->searchName = $name;
}
public function getData()
{
//Find the selected users.
return $this->model->findByCodeNumber($this->searchCode);
}
}
class ProductModel
{
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
public function findByCodeNumber($code)
{

Chapter - 04
Page - 38

Rz Rasel

Model View Controller (PHP)


//Find the selected users.
return $this->db->query(SELECT * FROM products WHERE code like :code,
array(:name, $code);
}
}
Neat and minimalist. All thats changed is the ViewModel. The view and controller can be reused. In this case, the template would still need to change too, of course.
PHP Code
class BlogListViewModel implements Listable
{
private $model;
public function __construct(BlogModel $model)
{

$this->model = $model;
}
public function getData()
{

return $this->model->findAll();
}
}
In this case, a controller would not even be required! The view would get its data from the
ViewModel and it wouldnt even matter that the controller didnt exist.
With minimal code, a lot different fairly substantial variations are possible due to having both
high flexibility and high reusability.
Heres one more example using something slightly more complex. Like part 1 pagination will
be used again, its simple and commonplace enough that everyone understands it, yet its nottrivial enough to provide a worthwhile demonstration.
PHP Code
interface Pageable
{
//Get the records using limit and offset
public function find($limit, $offset);
//The number of records which will be shown on each page
public function getRecordsPerPage();
//The page currently being shown
public function getCurrentPage();
//The total number of records being paged through.
//Used to calculate the total number of pages.
public function getTotalResults();
}
class PaginationView
{
private $model;
private $template;
public function __construct(Pageable $model, Template $template)
{

Chapter - 04
Page - 39

Rz Rasel

Model View Controller (PHP)


$this->model = $model;
$this->template = $template;

}
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

Model View Controller (PHP)


//Simple example, in reality the model would have a count method for performance reasons
return count($this->model->findByName($this->searchName));

}
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

Model View Controller (PHP)


the new keyword instead of factories/dependency injection, insecure code which is subject
to SQL injection and things which are considered bad practice. All this is for the sake of simplicity: The article is teaching the idea of views/view helpers not other best practices. Because
of this, please dont take code which is outside the scope of the article and use it without understanding the implications behind it.
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 - 04
Page - 42

Rz Rasel

Model View Controller (PHP)

ontents

05

PHP MVC Framework Basic Introduction


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . .
What is PHP MVC Framework? . . . . . . . . . . . . . . . . . . . .
How to implement PHP MVC Framework? . . . . . . . . . . . . . . .
Model in PHP MVC Framework . . . . . . . . . . . . . . . . . . . .
Code snippet (Book Class) . . . . . . . . . . . . . . . . . . . . .
Code snippet (Model Class). . . . . . . . . . . . . . . . . . . . .
Controller in PHP MVC Framework. . . . . . . . . . . . . . . . . .
Code snippet (controller class) . . . . . . . . . . . . . . . . . . .
View in PHP MVC Framework . . . . . . . . . . . . . . . . . . . .
Code snippet . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . .

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

Model View Controller (PHP)


Introduction
The Model View Controller pattern is the latest application development framework for developing desktop, mobile, and web applications. It is extremely useful in large scale applications
because in MVC, different parts (views, business logic and storage) of a system are developed
separately resulting in loosely coupled modular application. As a result, maintenance, flexibility, and scalability of a system increases and code becomes shorter and easier to read. A
lot of PHP frameworks are based on MVC patterns which already exist, but even using these
solutions require ample knowledge of PHP MVC Framework basics.
What is PHP MVC Framework?
In PHP MVC Framework, the html views, business logics controllers and data handling models
are developed separately, enabling the designers to work with the views without any concern
with the data and its handling; same goes for a programmer whose main focus is on developing the model. This makes PHP application components loosely coupled.
How to implement PHP MVC Framework?
Implementation of the PHP MVC Framework requires understanding of the terms model,
view and controller. Therefore, the following sections demonstrate the detailed description
of model, view and controller with the example of Book Selection application in which
a user selects an entry of book from a combo-box and selecting the value, which results in a
detailed description of the book. For simplicity, code is maintained in one file.
Model in PHP MVC Framework
In PHP MVC Framework, the model is responsible for managing the data that involves the storage and retrieval of entities like the user or a product order from the database or stored
arrays. The model is a part of application that involves processing the data required by an application. The model part is unaware of the business logic and its corresponding view.
In the example of a Book Selection model, part of PHP MVC framework is represented by
two classes Book and Model. The Book is an entity class used to keep the books data. The
model class is used to store and retrieve the books data.
Code snippet (Book Class)
<?php
class Book
{
public $name;
public $version;
public $yearOfPublish;
public function __construct($name, $version, $yearOfPublish)
{
$this->name = $name;
$this->version = $version;
$this->yearOfPublish = $yearOfPublish;
}
}
?>

Chapter - 05
Page - 44

Rz Rasel

Model View Controller (PHP)


Code snippet (Model Class)
<?php
class Model
{
public $text;
public function __construct()
{

$this->text = Book Selection;
}
public function getBookList()
{
return array (
PHP for Absolute Beginners => new Book(PHP for Absolute Beginners, 1.2, 1999),
Basic Introduction to PHP MVC => new Book(Basic Introduction to PHP MVC,
1.0, 2008),
Advanced PHP => new Book(Advanced PHP, 1.2, 2004),
Advanced PHP MVC => new Book(Advanced PHP MVC, 2.0, 2014)
);
}
public function getBook($name)
{
$allBooks = $this->getBookList();
return $allBooks [$name];
}
}
?>
In the above code snippets of PHP MVC framework example, the Book class is used to keep
the data of a books name, version and publishing year. The model class stores the books
data in the form of associative array with a method to return all the books data and a single
book filtered by the name attribute with addition of the text property that has the application name.
Controller in PHP MVC Framework
In PHP MVC framework, the controller takes an input from user as a request, processes and
analyzes this input, initializes and invokes the model, takes the model response and sends
it back to the respected view. So controller is a part of application that involves the logical
processes of the application also called the business logic. It acts as a middle layer for views
and models.
In the example of a Book Selection controller, part of PHP MVC framework is represented by
one class Controller. This class instantiates the model class and call the methods to retrieve
the books information based on the request nature.
Code snippet (controller class)
<?php
class Controller
{
private $model;
public function __construct(Model $model)
{

Chapter - 05
Page - 45

Rz Rasel

Model View Controller (PHP)

}
?>

$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

Model View Controller (PHP)


?>
<form method=GET action= >
<select name=book >
<?php
foreach ($books as $x => $x_value)
{

echo <option value=.$x.>.$x.</option>;
}
?>
</select>
<input type=submit value=Select>
</form>
In the above code snippet, the output method of controller is called to generate the name of
the application with the html heading tag. Next,the invoke method is called to retrieve the
books information. A combo-box is filled with the returned book names. When you click the
submit button, a request is created with a book name selected in a combo-box to the same
view, which displays details of selected book as output HTML page.
Codes All Together
The directories structure:
+rz-mvc
index.php
rz-mvc index.php
<?php
class Book
{
public $name;
public $version;
public $yearOfPublish;

}
?>

public function __construct($name, $version, $yearOfPublish)


{
$this->name = $name;
$this->version = $version;
$this->yearOfPublish = $yearOfPublish;
}

<?php
class Model
{
public $text;
public function __construct()
{

$this->text = Book Selection;
}
public function getBookList()
{

Chapter - 05
Page - 47

Rz Rasel

Model View Controller (PHP)


return array (
PHP for Absolute Beginners => new Book(PHP for Absolute Beginners, 1.2, 1999),
Basic Introduction to PHP MVC => new Book(Basic Introduction to PHP MVC,
1.0, 2008),
Advanced PHP => new Book(Advanced PHP, 1.2, 2004),
Advanced PHP MVC => new Book(Advanced PHP MVC, 2.0, 2014)
);

}
?>

}
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

Model View Controller (PHP)


}
?>

<form method=GET action= >


<select name=book >
<?php
foreach ($books as $x => $x_value)
{

echo <option value=.$x.>.$x.</option>;
}
?>
</select>
<input type=submit value=Select>
</form>
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 - 05
Page - 49

Rz Rasel

Model View Controller (PHP)

ontents

06

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

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Chapter - 06
Page - 50

Rz Rasel

Model View Controller (PHP)


MVC little history
Model-View-Controller (MVC) is probably one of the most quoted patterns in the web programming world in recent years. Anyone currently working in anything related to web application
development will have heard or read the acronym hundreds of times. Today, well clarify what
MVC means, and why it has become so popular.
MVC is not a design pattern, it is an Architectural pattern that describes a way to structure
our application and the responsibilities and interactions for each part in that structure.
It was first described in 1979 and, obviously, the context was a little bit different. The concept
of web application did not exist. Tim Berners Lee sowed the seeds of World Wide Web in the
early nineties and changed the world forever. The pattern we use today for web development
is an adaptation of the original pattern.
The wild popularization of this structure for web applications is due to its inclusion in two development frameworks that have become immensely popular: Struts and Ruby on Rails. These
two environments marked the way for the hundreds of frameworks created later.
MVC for Web Applications
The idea behind the Model-View-Controller architectural pattern is simple: we must have the
following responsibilities clearly separated in our application:

Handel data and business logic

Model

Present data to the user in any supported


format and layout

View

Receive user requests and call appropriate


resources to carry them out

Controller

The application is divided into these three main components, each one in charge of different
tasks.

Chapter - 06
Page - 51

Rz Rasel

Model View Controller (PHP)


Controller
The Controller manages the user requests (received as HTTP GET or POST requests when the
user clicks on GUI elements to perform actions). Its main function is to call and coordinate the
necessary resources/objects needed to perform the user action. Usually the controller will call
the appropriate model for the task and then selects the proper view.
Model
The Model is the data and the rules applying to that data, which represent concepts that the
application manages. In any software system, everything is modeled as data that we handle in
a certain way. What is a user, a message or a book for an application? Only data that must be
handled according to specific rules (date can not be in the future, e-mail must have a specific
format, name cannot be more than x characters long, etc).
The model gives the controller a data representation of whatever the user requested (a message, a list of books, a photo album, etc). This data model will be the same no matter how we
may want to present it to the user, thats why we can choose any available view to render it.
The model contains the most important part of our application logic, the logic that applies to
the problem we are dealing with (a forum, a shop, a bank, etc). The controller contains a more
internal-organizational logic for the application itself (more like housekeeping).
View
The View provides different ways to present the data received from the model. They may be
templates where that data is filled. There may be several different views and the controller
has to decide which one to use.
A web application is usually composed of a set of controllers, models and views. The controller
may be structured as a main controller that receives all requests and calls specific controllers
that handles actions for each case.
Lets See an Example
Suppose were developing an online book store. The user can perform actions such as: view
books, register, buy, add items to current order, create or delete books (if he is an administrator, etc.). Lets see what happens when the user clicks on the fantasy category to view the
titles we have available.
We will have a particular controller to handle all books-related actions (view, edit, create,
etc). Lets call it books_controller.php for this example. We will also have a model, for example
book_model.php, handling data and logic related to the items in the shop. Finally we will have
a series of views to present, for example, a list of books, a page to edit books, etc.
The following figure shows how the user request to view the fantasy books list is handled:

Chapter - 06
Page - 52

Rz Rasel

Model View Controller (PHP)

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

Model View Controller (PHP)


Apart from isolating the view from the business logic, the M-V-C separation reduces the complexity when designing large applications. The code is much more structured and therefore
easier maintain, test and reuse.
Ok, but Why a Framework?
When you use a framework, the basic structure for MVC is already prepared and you just
have to extend that structure, placing your files in the appropriate directory, to comply with
the Model-View-Controller pattern. Also you get a lot of functionality already written and
thoroughly tested.
Take cakePHP as an example MVC framework. Once you have it installed, youll see three main
directories:


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

Model View Controller (PHP)


Remember we had a book store and a curious user who wants to see the complete list of books
in the fantasy category. We said that the controller will be the one receiving the request and
coordinating the necessary actions.
So, when the user clicks, the browser will be requesting this url:
http://localhost/rz-mvc/books/list/fantasy
CakePHP likes to format URLs in the form /controller/action/param1/param2 , where action is
the function to call within the controller. In the old classic url format it would be:
http://localhost/rz-mvc/books_controller.php?action=list&category=fantasy
Controller
With the help of cakePHP framework, our controller will look something like this:
<?php
class BooksController extends AppController
{

function list($category)
{

$this->set(books, $this->Book->findAllByCategory($category));
}

function add() { ... ... }

function delete() { ... ... }

... ...
}
?>
Simple, isnt it?. This controller will be saved as books_controller.php and placed in /app/
controllers. It contains the list function, to perform the action in our example, but also other
functions to perform other book-related actions (add a new book, delete a book, etc).
The framework provides a lot of things for us and only one line is necessary to list the books.
We have base classes with the basic controller behavior already defined, so we inherit from
them (AppController which inherits from Controller).
All it has to do in the list action is call the model to get the data and then choose a view to
present it to the user. Lets explain how this is done.
this->Book is our Model, and this part:
$this->Book->findAllByCategory($category)
is telling the model to return the list of books in the selected category (well see the model
later).
The set method in the line:
$this->set(books, $this->Book->findAllByCategory($category));
Is the controller way to pass data to the view. It sets the books variable to the data returned

Chapter - 06
Page - 55

Rz Rasel

Model View Controller (PHP)


by the model and makes it accessible to the view.
Now we just have to render the view, but this will be done automatically by cakePHP if we want
the default view. If we need any other view we just have to call it explicitly using the render
method.
Model
The model is even more simple:
<?php
class Book extends AppModel
{
}
?>
Why empty? Because it inherits from a base class that provides necessary functionality and
we have followed the CakePHP name conventions to allow the framework to do other tasks
automatically. For example, cakePHP knows, based on names, that this model is used in
BooksController and that it will access a database table called books.
With this declaration only we have a book model capable of reading, deleting or saving data
from the database
The code will be saved as book.php and placed in /app/models.
View
All we have to do now is creating a view (at least one) for the list action. The view will have the
HTML code and a few (as few as possible) PHP lines to loop through the books array provided
by the model.
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
<?php foreach ($books as $book): ?>
<tr>
<td><?php echo $book[Book][title]; ?></td>
<td><?php echo $book[Book][author]; ?></td>
<td><?php echo $book[Book][price]; ?></td>
</tr>
<?php endforeach; ?>
</table>
As we can see, the view doesnt produce a complete page, just an HTML fragment (a table in
this case). This is because CakePHP provides another way to define the layout of the page,
and the views are inserted into that layout. The framework also provides us with some helper
objects to make common task easy when creating these HTML excerpts (insert forms, links,
Ajax or JavaScript).
We make this the default view saving it as list.ctp ( list is the name of the action and ctp means

Chapter - 06
Page - 56

Rz Rasel

Model View Controller (PHP)


cake template) and placing it in /app/views/books (inside books because these are views for
books controller actions).
And this completes the three components with the help of CakePHP framework!
Conclusion
We have learned what is probably the most commonly used architectural pattern today. We
must be aware though that when we talk about patterns in the programming world, we are
talking about flexible frames, to be tailored to the particular problem at hand. We will find
implementations introducing variations on the structure we have seen, but the important thing
is that, in the end, the pattern helps us gain a clear division between responsibilities and better maintainability, code-reuse, and testing.
We have also seen the advantages of using an MVC framework that provides us with a basic
MVC skeleton and a lot of functionality, improving our productivity and making the development process easier.
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 - 06
Page - 57

Rz Rasel

Model View Controller (PHP)

ontents

07

PHP MVC Pattern and Routing URLs


Routing and URLs. . . . . . . . . . . . . . . . . . . . . . . . . .
DRY (Dont Repeat Yourself) & Templates . . . . . . . . . . . . . .
Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

59
61
61
62

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Chapter - 07
Page - 58

Rz Rasel

Model View Controller (PHP)


Discussing MVC and PHP, where well discuss some of the considerations one must make when
using an MVC architecture.
Routing and URLs
Although MVC, in theory, should work flawlessly in all forms of computer programming, incorporating MVC on the web with PHP can be a bit tricky. The first problem is with URL routing.
URL routing is an aspect that was never considered when MVC was created, and so as the
Internet evolves and develops with the expansion of technology, so must the architecture patterns we use.
So what options do we have for solving the URL routing problem? One solution is to attempt to
preempt any URLs that your site or web app needs, storing them in permanent storage along
with information about which Model, View, and Controller to load for each page or section.
The system then gets the URL requested by the user and loads the specific components assigned for that page and gets to work. This is a perfectly feasible solution if you are creating a
portfolio site or a static website, which doesnt rely on dynamic URLs. For example:
<?php
$page = $_GET[page];
if(!empty($page))
{

$data = array(

about => array(model => AboutModel, view => AboutView, controller
=> AboutController),

portfolio => array(model => PortfolioModel, view => PortfolioView,
controller => PortfolioController)

);


foreach($data as $key => $components)
{

if($page == $key)
{

$model = $components[model];

$view = $components[view];

$controller = $components[controller];

break;
}
}


if(isset($model))
{

$m = new $model();

$c = new $controller($model);

$v = new $view($model);

echo $v->output();
}
}
?>
Our URLs would look like this:
http://localhost/rz-mvc/index.php?page=about

Chapter - 07
Page - 59

Rz Rasel

Model View Controller (PHP)


or
http://localhost/rz-mvc/index.php?page=portfolio
The example MVC system loads the specific Model, View, and Controller set for the requested page. If the URL parameter is about, then the About page will be displayed. If the
parameter is portfolio, the Portfolio page will be instead.
This is a basic example of static routing which, even through its very simple to set up. Comes
with some drawbacks. One of the most obvious drawbacks is the fact that scalability becomes
much harder, as the breadth of your site is constricted to the hard-coded array of pages.
In this static routing example, we simply pulled the class identification from an array, which
in turn acted as routing data coming from our permanent storage. Replacing the array with
elements turns our static routing into dynamic routing.
Despite the fact we pulled a key for each association in the array with a URL variable, the relationships with corresponding classes were already predefined; we couldnt mix and match between the values in each key with static routing. But why would we even want to do this? Well
for starters, we wouldnt have to hard code each section of our system. We can create sections
or pages just through creating a Model, View and Controller relationship. For example:
<?php
$model = $_GET[model];
$view = $_GET[view];
$controller = $_GET[controller];
$action = $_GET[action];
if(!(empty($model) || empty($view) || empty($controller) || empty($action)))
{

$m = new $model();

$c = new $controller($m, $action);

$v = new $view($m);

echo $v->output();
}
?>
Our new URL would now look like:
http://localhost/rz-mvc/index.php?controller=controllername&model=modelname&view=view
name&action=actionname
The action URL variable tells the system which function in the Controller to execute. It is
important to remember that when this function passes data to the Model, it passes a piece
of data to the Model that will in turn indicate which View and View Action to load. This can
be the action URL variable, but it can also be separate, or data collected by the Controller.
Remember to never allow the Controller to load or directly pass data to the View; it must
only interact with the Model and the Users inputs.
Both approaches have their pros and cons, with static routing being more stable, quicker to
implement, and allowing developers more control over the system, and with dynamic routing
allowing us to create a more effective system where there is huge potential for scalability and
portability.

Chapter - 07
Page - 60

Rz Rasel

Model View Controller (PHP)


Dynamic routing can, however, place more responsibility on the Controller than static routing, which can be seen as altering the traditional MVC pattern. Nevertheless, if dynamic routing is implemented correctly and effectively, is can make the Controller more desirable within
the system compared to using static routing.
DRY (Dont Repeat Yourself) & Templates
One of my main arguments for using the MVC pattern is the aim to make your overall system
as organized as possible. The most obvious way to do this is to reduce the amount of opportunities to have multiple instances of the same code. Any developer will agree that the worst
thing to find in any application is repetition of the same code. The practice of keeping your
code streamlined and using reusable components as much as possible is know as the DRY
philosophy Dont Repeat Yourself.
The DRY principle dictates that every piece of knowledge must have a single, unambiguous, authoritative representation within a system. The aim of DRY is to increase and explore
every possible avenue open to developers to make their system as dynamic and optimized
as possible. DRY principle implies that, if you need to write the same piece of code in many
places, instead of repeating the code at these places, create a separate method and use it
wherever required. This allows the system to become more optimized and introduces the possibility of caching within our systems to help improve the overall run time.
A correct implementation of DRY would imply that changing one element of the system does
not change unrelated elements, which makes DRY an important principle to work to when
developing with MVC patterns.
Templates
The word template might raise a few questions for those who have seen MVC web frameworks before, as most people lump the template part in with the View. As weve discussed
before, this is incorrect if you wish to stick with the traditional MVC pattern. Ideally, you would
have the View dealing with the data crunching and processing after collecting the data from
the Model. Therefore it only makes sense for your View component to select a template and
pass the data from the View into that template. That way it is ready to be displayed using a
block code layout, or with an echo, print, or any other outputting code in PHP. Whichever of
those methods you choose to use, the main thing to remember is that your data MUST be at a
state of readiness that you only need to print the data in the template. If you are doing other
data processing or crunching in the template your setup is wrong, and most likely, the MVC
setup is incorrect.
Heres a quick example of your view loading a template and pushing data to it:
<?php
class Model
{

public $tstring;


public function __construct()
{

$this->tstring = The string has been loaded through the template.;

$this->template = tpl/template.php;
}
}
?>

Chapter - 07
Page - 61

Rz Rasel

Model View Controller (PHP)


<?php
class View
{

private $model;


public function __construct($model)
{

$this->controller = $controller;

$this->model = $model;
}


public function output()
{

$data = <p> . $this->model->tstring .</p>;

require_once($this->model->template);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset=charset=utf-8>
<title>The Template name</title>
</head>
<body>
<h1><?php echo $data; ?></h1>
</body>
</html>
In addition the template is being passed through the model, which in principle can allow for
dynamic assignment of templates depending on what each particular View is meant to be
doing. This method of templating allows MVC systems to be expanded upon efficiently and
confidently, while giving us the option to split the back end development from the front end
development; an original goal of the MVC pattern.
Conclusion
The MVC pattern was a game changer when it was first used for desktop programming. It
was, and still is, a highly debated topic between developers with regard to interpreting certain
scenarios when developing with it. The debate becomes even more intense when you add PHP
and the web into the mix, which is a fantastic sign that more and more developers are becoming focused on improving development disciplines for PHP.
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 - 07
Page - 62

Rz Rasel

Model View Controller (PHP)

ontents

08

MVC Pattern and PHP


PHP MVC Pattern. . . . . . . . . . . . . . . . . . . . . . . . . .
Understanding MVC . . . . . . . . . . . . . . . . . . . . . . . . .
Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MVC in PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . .

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

Model View Controller (PHP)


PHP MVC Pattern
The Model View Control (MVC) pattern, originally formulated in the late 1970s, is a software
architecture pattern built on the basis of keeping the presentation of data separate from the
methods that interact with the data. In theory, a well-developed MVC system should allow a
front-end developer and a back-end developer to work on the same system without interfering, sharing, or editing files either party is working on.
Even though MVC was originally designed for personal computing, it has been adapted and is
widely used by web developers due to its emphasis on separation of concerns, and thus indirectly, reusable code. The pattern encourages the development of modular systems, allowing
developers to quickly update, add, or even remove functionality.
Now I will go the basic principles of MVC, a run through the definition of the pattern and a
quick example of MVC in PHP. Its definitely read for anyone who has never coding with MVC
before or those want to brush up on previous MVC development skills.
Understanding MVC
The patterns title is a collation of its three core parts: Model, View, and Controller. A visual
representation of a complete and correct MVC pattern looks like the following diagram:

Chapter - 08
Page - 64

Rz Rasel

Model View Controller (PHP)

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

Model View Controller (PHP)


system which handles the data process. The Model must act as a gatekeeper to the data itself,
asking no questions but accepting all requests which comes its way. Often the most complex
part of the MVC system, the Model component is also the pinnacle of the whole system since
without it there isnt a connection between the Controller and the View.
View
The View is where data, requested from the Model, is viewed and its final output is determined. Traditionally in web apps built using MVC, the View is the part of the system where the
HTML is generated and displayed. The View also ignites reactions from the user, who then goes
on to interact with the Controller. The basic example of this is a button generated by a View,
which a user clicks and triggers an action in the Controller.
There are some misconceptions held about View components, particularly by web developers
using the MVC pattern to build their application. For example, many mistake the View as having no connection whatsoever to the Model and that all of the data displayed by the View is
passed from the Controller. In reality, this flow disregards the theory behind the MVC pattern
completely. Fabio Cevascos article The CakePHP Framework: Your First Bite demonstrates this
confused approach to MVC in the CakePHP framework, an example of the many non-traditional
MVC PHP frameworks available:
It is important to note that in order to correctly apply the MVC architecture, there must be
no interaction between models and views: all the logic is handled by controllers
Furthermore, the description of Views as a template file is inaccurate. However, as Tom Butler
points out, this is not one persons fault but a multitude of errors by a multitude of developers which result in developers learning MVC incorrectly. They then go on to educate others
incorrectly. The View is really much more than just a template, however modern MVC inspired
frameworks have bastardised the view almost to the point that no one really cares whether or
not a framework actually adheres to the correct MVC pattern or not.
Its also important to remember that the View part is never given data by the Controller. As
I mentioned when discussing the Model, there is no direct relationship between the View and
the Controller without the Model in between them.
Controller
The final component of the triad is the Controller. Its job is to handle data that the user inputs
or submits, and update the Model accordingly. The Controllers life blood is the user; without
user interactions, the Controller has no purpose. It is the only part of the pattern the user
should be interacting with.
The Controller can be summed up simply as a collector of information,
on to the Model to be organized for storage, and does not contain any
needed to collect the input. The Controller is also only connected to a
single Model, making it a one way data flow system, with handshakes
point of data exchange.

which then passes it


logic other than that
single View and to a
and signoffs at each

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

Model View Controller (PHP)


tions that give it the sole responsibility of crunching, passing, and processing data from the
Model to the View, whereas in the MVC pattern this relationship should be kept between the
Model and the View.
MVC in PHP
It is possible to write a web application in PHP whose architecture is based on the MVC pattern.
Lets start with a bare bones example:
<?php
class Model
{

public $string;

public function __construct()
{

$this->string = MVC + PHP = Awesome!;
}
}
?>
<?php
class View
{

private $model;

private $controller;


public function __construct($controller,$model)
{

$this->controller = $controller;

$this->model = $model;
}

public function output()
{

return <p> . $this->model->string . </p>;
}
}
?>
<?php
class Controller
{

private $model;


public function __construct($model)
{

$this->model = $model;
}
}
?>
We have our project started with some very basic classes for each part of the pattern. Now we
need to set up the relationships between them:
<?php

Chapter - 08
Page - 67

Rz Rasel

Model View Controller (PHP)


$model = new Model();
$controller = new Controller($model);
$view = new View($controller, $model);
echo $view->output();
?>
As you can see in the example above, we dont have any Controller-specific functionality because we dont have any user interactions defined with our application. The View holds all of
the functionality as the example is purely for display purposes.
Lets now expand the example to show how we would add functionality to the controller,
thereby adding interactivity to the application:
<?php
class Model
{
public $string;
public function __construct()
{
$this->string = MVC + PHP = Awesome, click here!;
}
}
?>
<?php
class View
{

private $model;

private $controller;


public function __construct($controller,$model)
{

$this->controller = $controller;

$this->model = $model;
}


public function output()
{

return <p><a href=mvc.php?action=clicked . $this->model->string . </a></p>;
}
}
?>
<?php
class Controller
{

private $model;

public function __construct($model)
{

$this->model = $model;
}

public function clicked()
{

$this->model->string = Updated Data, thanks to MVC and PHP!;

Chapter - 08
Page - 68

Rz Rasel

Model View Controller (PHP)


}
}
?>
Weve enhanced the application with some basic functionality. Setting up the relationship between our components now looks like this:
<?php
$model = new Model();
$controller = new Controller($model);
$view = new View($controller, $model);
if (isset($_GET[action]) && !empty($_GET[action]))
{

$controller->{$_GET[action]}();
}
echo $view->output();
?>
Run the code and when you click on the link youll be able to see the string change its data.
Conclusion
Weve covered the basic theory behind the MVC pattern and have produced a very basic MVC
application, but we still have a long way to go before we get into any nitty-gritty functionality.
Next up in the series well cover some of the choices you face when trying to create a true MVC
application on the web in PHP. Stay tuned!
Codes All Together
The directories structure:
+rz-mvc
index.php
rz-mvc index.php
<?php
class Model
{
public $string;
public function __construct()
{
$this->string = MVC + PHP = Awesome, click here!;
}
}
?>
<?php
class View
{

private $model;

private $controller;

Chapter - 08
Page - 69

Rz Rasel

Model View Controller (PHP)




public function __construct($controller,$model)
{

$this->controller = $controller;

$this->model = $model;
}


public function output()
{

return <p><a href=mvc.php?action=clicked . $this->model->string . </a></p>;
}
}
?>
<?php
class Controller
{

private $model;

public function __construct($model)
{

$this->model = $model;
}

public function clicked()
{

$this->model->string = Updated Data, thanks to MVC and PHP!;
}
}
?>
<?php
$model = new Model();
$controller = new Controller($model);
$view = new View($controller, $model);
if (isset($_GET[action]) && !empty($_GET[action]))
{

$controller->{$_GET[action]}();
}
echo $view->output();
?>
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 - 08
Page - 70

Rz Rasel

Model View Controller (PHP)

ontents

09

MVC in PHP Real world program


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Converting currencies - The Model . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Enabling user input - The Controller. . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . .

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

Model View Controller (PHP)


Introduction
This is a step by step tutorial for implementing MVC in PHP in a real world application. Something you can see be developed one step at a time to produced a real application: The application will be a currency converter. It will convert from a chosen currency to several others and
display the values in each currency.
This example is lightweight MVC application. At the end youll understand the proper separation of concers of MVC and at the same time, be aware of the limitations of assuming the
domain model and MVC model are the same thing.
Converting currencies - The Model
Before even starting worrying about MVC or the structure of the application, the base problem
needs to be solved: doing the currency conversion. For this I can create a simple class:
PHP Code
class CurrencyConverter
{
private $baseValue = 0;
private $rates = array(GBP => 1.0,
USD => 0.6,
EUR => 0.83,
YEN => 0.0058);
public function get($currency)
{
if(isset($this->rates[$currency]))
{
$rate = 1/$this->rates[$currency];
return round($this->baseValue * $rate, 2);
}
else return 0;
}
public function set($amount, $currency = GBP)
{
if (isset($this->rates[$currency]))
{

$this->baseValue = $amount * $this->rates[$currency];
}
}
}
As you can see, this stores the exchange rates relative to GBP (British Pounds) and performs
the conversion. It stores a specific amount always stored as the value in GBP. However, the
base value is not directly accessible. The maths involved and implementation of this class isnt
important, what is important is that the class can be used to do conversions like this:
PHP Code
$currencyConverter = new CurrencyConverter;
$currencyConverter->set(100, GBP);
echo 100 GBP is:;
echo $currencyConverter->get(USD) . USD / ;

Chapter - 09
Page - 72

Rz Rasel

Model View Controller (PHP)


echo $currencyConverter->get(EUR) . EUR / ;
echo $currencyConverter->get(YEN) . YEN;
Alternatively, you could convert USD to other currencies using:
PHP Code
$currencyConverter = new CurrencyConverter;
$currencyConverter->set(100, USD);
echo 100 USD is: ;
echo $currencyConverter->get(GBP) . GBP / ;
echo $currencyConverter->get(EUR) . EUR / ;
echo $currencyConverter->get(YEN) . YEN;
This converter works without any knowledge of how it will be used, the architecture it might
be used in and can work as its own standalone component.
The View
Now that the domain model is working successfully the next step is to create the View. Since
the currency converter will require the user to type in a value in the currency theyre converting from an input box will be required as well as a submit button for them to press. Its probably worth displaying the From currency as well.
The view will need to know which currency its dealing with. In this instance, well start with
GBP.
The view might look something like this:
PHP Code
class CurrencyConverterView
{
private $currency;
public function __construct($currency)
{

$this->currency = $currency;
}
public function output()
{
$html = <form action=?action=convert method=post><input name=currency type=hidden
value= . $this->currency ./><label> . $this->currency .:</label><input name=amount type=text
value=/><input type=submit value=Convert/></form>;
return $html;
}
}
Which when instantiated using the code:
PHP Code
$view = new CurrencyConverterView(GBP);
echo $view->output();

Chapter - 09
Page - 73

Rz Rasel

Model View Controller (PHP)


At the moment its not actually displaying anything meaningful as it doesnt know about the
converter. The next step is to pass it the model, and have it display the value which is in the
model:
PHP Code
class CurrencyConverterView
{
private $converter;
private $currency;
public function __construct(CurrencyConverter $converter, $currency)
{
$this->converter = $converter;
$this->currency = $currency;
}
public function output()
{
$html = <form action=?action=convert method=post><input name=currency type=hidden
value= . $this->currency ./><label> . $this->currency .:</label><input name=amount type=text
value= . $this->converter->get($this->currency) . /><input type=submit value=Convert/></form>;
return $html;
}
}
The view can now display currencies. Using the code:
PHP Code
$currencyConverter = new CurrencyConverter;
$view = new CurrencyConverterView($currencyConverter, GBP);
echo $view->output();
This is not very informative. But we can test it using by setting a value in the model and displaying a different currency:
PHP Code
$currencyConverter = new CurrencyConverter; $currencyConverter->set(100, GBP);
$view = new CurrencyConverterView($currencyConverter, EUR);
echo $view->output();
Which is correctly displaying the EUR value of 100 GBP. On its own, this isnt very useful. However, because MVC is all about reusability, the View can be reused with the other currencies:
PHP Code
$currencyConverter = new CurrencyConverter;
$currencyConverter->set(100, GBP);
$gbpView = new CurrencyConverterView($currencyConverter, GBP);
echo $gbpView->output();
$usdView = new CurrencyConverterView($currencyConverter, USD);
echo $usdView->output();

Chapter - 09
Page - 74

Rz Rasel

Model View Controller (PHP)


$eurView = new CurrencyConverterView($currencyConverter, EUR);
echo $eurView->output();
$yenView = new CurrencyConverterView($currencyConverter, YEN);
echo $yenView->output();
By reusing the view multiple times, the data from the model can be shown in each currency.
Enabling user input - The Controller
The final piece of the puzzle is making the Convert button work. This is the last step in MVC
and why Model-View-Controller is MVC instead of CVM. The controller needs to take user input
and update the model in some way. The controller could look like this:
PHP Code
class CurrencyConverterController
{
private $currencyConverter;
public function __construct(CurrencyConverter $currencyConverter)
{

$this->currencyConverter = $currencyConverter;
}
public function convert($request)
{
if(isset($request[currency]) && isset($request[amount]))
{
$this->currencyConverter->set($request[amount], $request[currency]);
}
}
}
This uses the form field names which we already created in the view. In order to make the
controller reusable and testable, it doesnt use $_POST directly but takes an array which in
this example is passed in as an argument.
The application can now be initialised with the following code:
PHP Code
$model = new CurrencyConverter();
$controller = new CurrencyConverterController($model);
//Check for presence of $_GET[action] to see if a controller action is required
if(isset($_GET[action])) $controller->{$_GET[action]}($_POST);
$gbpView = new CurrencyConverterView($model, GBP);
echo $gbpView->output();
$usdView = new CurrencyConverterView($model, USD);
echo $usdView->output();
$eurView = new CurrencyConverterView($model, EUR);

Chapter - 09
Page - 75

Rz Rasel

Model View Controller (PHP)


echo $eurView->output();
$yenView = new CurrencyConverterView($model, YEN);
echo $yenView->output();
And the conversion will take place based on which convert button you press. Try it yourself.
Conclusion
This is an example of using MVC to solve a real world problem. Some of the key things to note
about implementing MVC are that, for this application:
The same view class is instantiated 4 times
The controller is only instantiated once and used by all the views
The view can be used without a controller (but user actions do not work)
The controller doesnt interract with the view at all
Because the controller isnt feeding information to the view or directing program flow, the
controller doesnt need to be instantiated separately for each instance of the view
As noted earlier, there are a few limitations with this approach because the Domain Model has
been used as the MVC model.
Codes All Together
The directories structure:
+rz-mvc
index.php
rz-mvc index.php
<?php
//Model
class CurrencyConverter
{

private $baseValue = 0;

private $rates = array(

GBP => 1.0,

USD => 0.6,

EUR => 0.83,

YEN => 0.0058

);


public function get($currency)
{

if(isset($this->rates[$currency]))
{

$rate = 1/$this->rates[$currency];

return round($this->baseValue * $rate, 2);
}

else return 0;
}


public function set($amount, $currency = GBP)
{

Chapter - 09
Page - 76

Rz Rasel

Model View Controller (PHP)



if(isset($this->rates[$currency]))
{

$this->baseValue = $amount * $this->rates[$currency];
}
}
}
//View
class CurrencyConverterView
{

private $converter;

private $currency;


public function __construct(CurrencyConverter $converter, $currency)
{

$this->converter = $converter;

$this->currency = $currency;
}

public function output()
{

$html = <form action=?action=convert method=post>

<input name=currency type=hidden value= . $this->currency . />

<label> . $this->currency .:</label>

<input name=amount type=text value= . $this->converter->get($this->currency) .
/>

<input type=submit value=Convert />

</form>;

return $html;
}
}
//Controller
class CurrencyConverterController
{

private $model;

public function __construct($model)
{

$this->model = $model;
}

public function convert($request)
{

if (isset($request[currency]) && isset($request[amount]))
{

$this->model->set($request[amount], $request[currency]);
}
}
}
//Application initialisation/entry point. In Java, this would be the static main method.
$model = new CurrencyConverter();
$controller = new CurrencyConverterController($model);
//If one of the forms has been submitted, call the relevant controller action

Chapter - 09
Page - 77

Rz Rasel

Model View Controller (PHP)


if (isset($_GET[action])) $controller->{$_GET[action]}($_POST);
$gbpView = new CurrencyConverterView($model, GBP);
echo $gbpView->output();
$usdView = new CurrencyConverterView($model, USD);
echo $usdView->output();
$eurView = new CurrencyConverterView($model, EUR);
echo $eurView->output();
$yenView = new CurrencyConverterView($model, YEN);
echo $yenView->output();
?>
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 - 09
Page - 78

Rz Rasel

Model View Controller (PHP)

ontents

10

PHP Model View Controller


PHP Model View Controller . . . . . . . . . . . . . . . . . . . . .
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model and Entity Classes. . . . . . . . . . . . . . . . . . . . . .
View (Presentation) . . . . . . . . . . . . . . . . . . . . . . . . .
viewbook.php . . . . . . . . . . . . . . . . . . . . . . . . . . .
booklist.php. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . .

80
81
82
83
84
84
85

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Chapter - 10
Page - 79

Rz Rasel

Model View Controller (PHP)


PHP Model View Controller
The model view controller pattern is the most used pattern for todays world web applications.
It has been used for the first time in Smalltalk and then adopted and popularized by Java. At
present there are more than a dozen of PHP web frameworks based on MVC pattern.
Despite the fact that the MVC pattern is very popular in PHP.
The MVC pattern separates an application in 3 modules: Model, View and Controller:
The model is responsible to manage the data; it stores and retrieves entities used by
an application, usually from a database, and contains the logic implemented by the application.
The view (presentation) is responsible to display the data provided by the model in a
specific format. It has a similar usage with the template modules present in some popular
web applications.
The controller handles the model and view layers to work together. The controller receives a request from the client, invokes the model to perform the requested operations
and sends the data to the View. The view formats the data to be presented to the user, in
a web application as an html output.
The above figure contains the MVC Collaboration Diagram, where the links and dependencies
between figures can be observed:

Client

http Request
http Response

Controllr

send Formatted Response

request Data Objects


return

Model

send Model Data Objects

View

This simple structure, putting each MVC module in one folder:

Chapter - 10
Page - 80

Rz Rasel

Model View Controller (PHP)


rz-mvc
controller
Controller.php
model
Book.php
Model.php
view
booklist.php
viewbook.php
index.php
Controller
The controller is the first thing which takes a request, parses it, initializes and invoke the
model and takes the model response and sends it to the presentation layer. Its practically the
liant between the Model and the View, a small framework where Model and View are plugged
in. In this MVC implementation the controller is implemented by only one class, named controller. The application entry point will be index.php. The index php file will delegate all the
requests to the controller:
// index.php file
include_once(controller/Controller.php);
$controller = new Controller();
$controller->invoke();
Our Controller class has only one function and the constructor. The constructor instantiates a
model class and when a request is done, the controller decides which data is required from the
model. Then it calls the model class to retrieve the data. After that it calls the corresponding
passing the data coming from the model. The code is extremely simple. Note that the controller does not know anything about the database or about how the page is generated.
include_once(model/Model.php);
class Controller
{
public $model;
public function __construct()
{

$this->model = new Model();
}
public function invoke()
{
if (!isset($_GET[book]))
{
// no special book is requested, well show a list of all available books
$books = $this->model->getBookList();
include view/booklist.php;
}
Chapter - 10
Page - 81

Rz Rasel

Model View Controller (PHP)

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

send Data retrieved from model


http Response

formate Output

Model and Entity Classes


The Model represents the data and the logic of an application, its call business logic. Usually,
its responsible for:
storing, deleting, updating the application data. Generally it includes the database operations, but implementing the same operations invoking external web services or APIs is
not an unusual at all.
encapsulating the application logic. This is the layer that should implement all the logic
of the application. The most common mistakes are to implement application logic operations inside the controller or the view(presentation) layer.
In our example the model is represented by 2 classes: the Model class and a Book class.
The model doesnt need any other presentation. The Book class is an entity class. This class
should be exposed to the View layer and represents the format exported by the Model view.
In a good implementation of the MVC pattern only entity classes should be exposed by the
model and they should not encapsulate any business logic. Their solely purpose is to keep
data. Depending on implementation Entity objects can be replaced by xml or json chunk of
data. In the above snippet you can notice how Model is returning a specific book, or a list of
all available books:
include_once(model/Book.php);

Chapter - 10
Page - 82

Rz Rasel

Model View Controller (PHP)


class Model
{
public function getBookList()
{
// here goes some hardcoded values to simulate the database
return array(
Jungle Book => new Book(Jungle Book, R. Kipling, A classic
book.),
Moonwalker => new Book(Moonwalker, J. Walker, ),
PHP for Dummies => new Book(PHP for Dummies, Some Smart Guy, )
);
}
public function getBook($title)
{
// we use the previous function to get all the books and then we return the
requested one.
// in a real life scenario this will be done through a db select command
$allBooks = $this->getBookList();
return $allBooks[$title];
}
}
In our example the model layer includes the Book class. In a real scenario, the model will
include all the entities and the classes to persist data into the database, and the classes encapsulating the business logic.
class Book
{
public $title;
public $author;
public $description;

public function __construct($title, $author, $description)


{
$this->title = $title;
$this->author = $author;
$this->description = $description;
}

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

Model View Controller (PHP)


In our example the view contains only 2 files one for displaying one book and the other one
for displaying a list of books.
viewbook.php
<html>
<head></head>
<body>
<?php

echo Title: . $book->title . <br/>;

echo Author: . $book->author . <br/>;

echo Description: . $book->description . <br/>;
?>
</body>
</html>
booklist.php
<html>
<head>
</head>
<body>

<table>

<tbody>

<tr>

<td>Title</td>

<td>Author</td>

<td>Description</td>
</tr>
</tbody>
<?php

foreach ($books as $title => $book)
{

echo <tr><td><a href=index.php?book=.$book->title.>.$book->title.</a></
td><td>.$book->author.</td><td>.$book->description.</td></tr>;
}
?>
</table>
</body>
</html>
The above example is a simplified implementation in PHP. Most of the PHP web frameworks
based on MVC have similar implementations, in a much better shape. However, the possibility
of MVC pattern are endless. For example different layers can be implemented in different languages or distributed on different machines. AJAX applications can implements the View layer
directly in Javascript in the browser, invoking JSON services. The controller can be partially
implemented on client, partially on server.
This post should not be ended before enumerating the advantages of Model View Controller
pattern:

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

Model View Controller (PHP)


cation can be transformed in a smart client application just by writing a new View module,
or an application can use web services in the backend instead of a database, just replacing
the model module.
each module can be tested and debugged separately.
Codes All Together
The directories structure:
+rz-mvc
+controller
| Controller.php
+model
| Book.php
| Model.php
+view
| booklist.php
| viewbook.php
index.php
rz-mvc controller Controller.php
<?php
include_once(model/Model.php);
class Controller
{
public $model;
public function __construct()
{
$this->model = new Model();
}
public function invoke()
{
if(!isset($_GET[book]))
{
// no special book is requested, well show a list of all available books
$books = $this->model->getBookList();
include view/booklist.php;
}
else
{
// show the requested book
$book = $this->model->getBook($_GET[book]);
include view/viewbook.php;
}
}
}
?>
rz-mvc model Book.php
<?php
class Book
{
public $title;
public $author;
public $description;

Chapter - 10
Page - 85

Rz Rasel

Model View Controller (PHP)

}
?>

public function __construct($title, $author, $description)


{
$this->title = $title;
$this->author = $author;
$this->description = $description;
}

rz-mvc model Model.php


<?php
include_once(model/Book.php);
class Model
{
public function getBookList()
{
// here goes some hardcoded values to simulate the database
return array(
Jungle Book => new Book(Jungle Book, R. Kipling, A classic
book.),
Moonwalker => new Book(Moonwalker, J. Walker, ),
PHP for Dummies => new Book(PHP for Dummies, Some Smart Guy, )
);
}
public function getBook($title)
{
// we use the previous function to get all the books and then we return the
requested one.
// in a real life scenario this will be done through a db select command
$allBooks = $this->getBookList();
return $allBooks[$title];
}
}
?>
rz-mvc view booklist.php
<html>
<head></head>
<body>
<table>
<tr><td>Title</td><td>Author</td><td>Description</td></tr>
<?php
foreach($books as $title => $book)
{
echo <tr><td><a href=index.php?book=.$book->title.>.$book->title.</a></td><td>.$book>author.</td><td>.$book->description.</td></tr>;
}
?>
</table>
</body>
</html>
rz-mvc view viewbook.php
<html>

Chapter - 10
Page - 86

Rz Rasel

Model View Controller (PHP)


<head></head>
<body>
<?php
echo Title: . $book->title . <br/>;
echo Author: . $book->author . <br/>;
echo Description: . $book->description . <br/>;
?>
</body>
</html>
rz-mvc index.php
<?php
include_once(controller/Controller.php);
$controller = new Controller();
$controller->invoke();
?>
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 - 10
Page - 87

Rz Rasel

Potrebbero piacerti anche