Top Banner

of 87

PHP Model View Controller 1st Edition Full

Jun 01, 2018

Download

Documents

Rz Rasel
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/9/2019 PHP Model View Controller 1st Edition Full

    1/87

    PHPMODEL VIEW CONTROLLER

    DINNER TIME HAND NOTE

    RZ RASEL

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    2/87

    Dinner Time Hand Note

    PHP Model View Controller

    Rz Rasel

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    3/87

    Dinner Time Hand NotePHP Model View ControllerDESIGN AND DEVELOPMENT

    1st Edition

    Rz Rasel

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    4/87

    Copyright by Rz Rasel

    All rights reserved. No part of this book may be reproduced, distributed, or transmitted inany form or by any means, including photocopying, recording, or other electronic or mechani-cal methods, without the prior written permission of the writer, except in the case of briefquotations embodied in critical reviews and certain other noncommercial uses permitted bycopyright law. For permission requests, write to the writer, addressed Attention: PermissionsCoordinator, at the address below.

    [email protected]

    1st Edition: August 2014

    Cover Illustration Copyright by Rz Rasel ([email protected])Cover design by Rz Rasel.Book design by Rz RaselEditing by Rz RaselChapter opening illustrations Rz Rasel

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    5/87

    AuthorRz Rasel

    OthersCallum Hopkins

    Kasia Mikoluk

    Tom Butler

    Pablo Pastor

    Rz Rasel (Rashed - Uz - Zaman) is a Software Engineer. Back-endand Front-end developer web experience. Also working in PHP,Android, Database like Sql, MySql, Sqlite. Web developer, Webdesigner, and blogger. Contact e-mail:- [email protected].

    Callum Hopkins is a designer and front-end developer web expe-rience and a Bachelors degree in Design for Digital Media. Withknowledge in both design and development, he is able to inu-ence both sides of the web building process.

    Kasia Mikoluk is a web developer.

    Tom Butler work as a Web Developer (Specialising mainly in PHP)for a web design agency. Also a part time lecturer. Tom Butlerhave an interest in programming since messing around with thecode for various computer games since he was about twelve. Heconsider it an art more than a science and love to explore the cre-ative side more than the functional side of the subject.

    Pablo Pastor is a web developer.

    CREDITS

    I would like to thanks all of them.

    I would like to thanks all of them.

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    6/87

    Rz Rasel (Rashed - Uz - Zaman) Software Engineer. Software developer, Software designer,System designer, Database designer, Web developer, Web designer, and blogger born in Ban-gladesh, and now living in Bangladesh.

    Rz Rasel unearthed the World Wide Web and started creating web sites many years. Workingin software frim in bangladesh as android developer, web developer with system analysis and

    design, database design. Write blogs in google blogger, WordPress (https://arzrasel.word-press.com). A few years later, Rz Rasel created his rst blog (https://arzrasel.wordpress.com).

    In his spare time, he enjoys to write story, poem. You can visit his home page at https://arz-rasel.wordpress.com or e-mail him at [email protected].

    Rz Rasel

    ABOUT AUTHOR

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    7/87

    When I am trying to learn about Model View Controller (MVC) I dont get any proper or com-plete book for MVC. I get a lot of book about Model View Controller (MVC), but that are notfor 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 ModelView 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 nowI put all together my hand note I am trying to help all of them who want/interested to learnabout MVC.

    Rz Rasel

    AUTHORS NOTE

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    8/87

    Get in touch with writer

    WordPress Blog:- https://arzrasel.wordpress.comFacebook:- https://www.facebook.com/rzprogrammingFacebook:- https://www.facebook.com/groups/merzrasel/Facebook:- https://www.facebook.com/groups/rzprogrammer/E-mail:- [email protected]

    Rz Rasel

    GET IN TOUCH

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    9/87

    01

    02

    03

    CONTENTS

    MVC ARCHITECTURE

    MVC Basic Architecture . . . . . . . . . . . . . . . . . . . . . . . 15

    The model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    The view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    The controller . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    UNDERSTANDING MODEL VIEW CONTROLLERUnderstanding the Model View Controller (MVC) . . . . . . . . . . . 18

    A Brief History of Model View Controller (MVC) . . . . . . . . . . . . 18

    So What Exactly is a Model View Controller? . . . . . . . . . . . . . 18

    MVC in PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    THE VIEW GETS ITS OWN DATA FROM THE MODEL

    Abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    MVC - Model View Confusion . . . . . . . . . . . . . . . . . . . . 23

    The view is more than a template . . . . . . . . . . . . . . . . . . 23

    Example 1 PHP Code . . . . . . . . . . . . . . . . . . . . . . . . 24

    Example 2 PHP Code . . . . . . . . . . . . . . . . . . . . . . . . 24

    Binding logic is problematic . . . . . . . . . . . . . . . . . . . . . 24

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

    When the view really needs the model . . . . . . . . . . . . . . . 25

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

    Better reusability . . . . . . . . . . . . . . . . . . . . . . . . . 26

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    10/87

    04

    05

    MVC MODELS ARE NOT DOMAIN MODELS

    Flexibility vs Reusability . . . . . . . . . . . . . . . . . . . . . . 32

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    Terminology: ViewModels View Helpers, Models . . . . . . . . . . . 35

    What is a view helper? . . . . . . . . . . . . . . . . . . . . . . . 35

    An Implementation . . . . . . . . . . . . . . . . . . . . . . . . 35

    The Template . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    The View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    The ViewModel . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    A small disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . 41

    PHP MVC FRAMEWORK BASIC INTRODUCTION

    Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

    What is PHP MVC Framework? . . . . . . . . . . . . . . . . . . . 44

    How to implement PHP MVC Framework? . . . . . . . . . . . . . . 44

    Model in PHP MVC Framework . . . . . . . . . . . . . . . . . . . 44

    Code snippet (Book Class) . . . . . . . . . . . . . . . . . . . . . 44

    Code snippet (Model Class) . . . . . . . . . . . . . . . . . . . . . 45

    Controller in PHP MVC Framework . . . . . . . . . . . . . . . . . . 45

    Code snippet (controller class) . . . . . . . . . . . . . . . . . . . 45

    View in PHP MVC Framework . . . . . . . . . . . . . . . . . . . . 46

    CONTENTS

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    11/87

    0006

    07

    08

    Code snippet . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

    Codes All Together . . . . . . . . . . . . . . . . . . . . . . . . . 47

    MVC LITTLE HISTORY AND WEB APPLICATIONS

    MVC little history . . . . . . . . . . . . . . . . . . . . . . . . . 51

    MVC for Web Applications . . . . . . . . . . . . . . . . . . . . . 51

    Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    Lets See an Example . . . . . . . . . . . . . . . . . . . . . . . 52

    What are the Advantages? . . . . . . . . . . . . . . . . . . . . . 53

    Ok, but Why a Framework? . . . . . . . . . . . . . . . . . . . . . 54

    Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

    Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

    PHP MVC PATTERN AND ROUTING URLS

    Routing and URLs . . . . . . . . . . . . . . . . . . . . . . . . . 59

    DRY (Dont Repeat Yourself) & Templates . . . . . . . . . . . . . . 61

    Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

    Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

    MVC PATTERN AND PHP

    PHP MVC Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . 64

    Understanding MVC . . . . . . . . . . . . . . . . . . . . . . . . 64

    Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

    View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

    Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

    MVC in PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

    Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    Codes All Together . . . . . . . . . . . . . . . . . . . . . . . . . 69

    CONTENTS

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    12/87

    09

    10

    MVC IN PHP REAL WORLD PROGRAM

    Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

    Converting currencies - The Model . . . . . . . . . . . . . . . . . 72

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

    The View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

    Enabling user input - The Controller . . . . . . . . . . . . . . . . . 75

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

    Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76Codes All Together . . . . . . . . . . . . . . . . . . . . . . . . . 76

    PHP MODEL VIEW CONTROLLER

    PHP Model View Controller . . . . . . . . . . . . . . . . . . . . . 80

    Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

    Model and Entity Classes . . . . . . . . . . . . . . . . . . . . . . 82

    View (Presentation) . . . . . . . . . . . . . . . . . . . . . . . . 83

    viewbook.php . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

    booklist.php . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

    Codes All Together . . . . . . . . . . . . . . . . . . . . . . . . . 85

    [email protected] Free To Ask Question You May Have

    CONTENTS

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    13/87

    Model View Controller (PHP)

    Rz Rasel

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    14/87

    01CONTENTS

    MVC ARCHITECTURE

    MVC Basic Architecture . . . . . . . . . . . . . . . . . . . . . . . 15

    The model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    The view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    The controller . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    [email protected] Free To Ask Question You May Have

    Model View Controller (PHP)

    Rz RaselChapter - 01Page - 14

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    15/87

    MVC Basic Architecture

    Model View Controller or MVCas it is popularly called, is a software design pattern for de-veloping web applications. A Model View Controller pattern is made up of the following threeparts:

    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 supportsseparation of concerns. Here the Controllerreceives all requests for the application and thenworks with the Modelto prepare any data needed by the View. The Viewthen uses the dataprepared by the to generate a nal presentable response. The MVCabstraction can be graphi-cally represented as follows.

    Model

    View

    Controller

    User

    The model

    The model is responsible for managing the data of the application. It responds to the requestfrom 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

    Model View Controller (PHP)

    Rz RaselChapter - 01Page - 15

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    16/87

    data. They are script based templating systems like JSP, ASP, PHP and very easy to integratewith AJAX technology.

    The controller

    The controller is responsible for responding to user input and perform interactions on the datamodel objects. The controller receives the input, it validates the input and then performs the

    business operation that modies the state of the data model.

    [email protected] YOUVE GOT SUGGESTIONS FOR IMPROVEMENTS ID LOVE TO SEE. DONT HESI-

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

    Model View Controller (PHP)

    Rz RaselChapter - 01Page - 16

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    17/87

    02CONTENTS

    UNDERSTANDING MODEL VIEW CONTROLLER

    Understanding the Model View Controller (MVC) . . . . . . . . . . . 18

    A Brief History of Model View Controller (MVC) . . . . . . . . . . . . 18

    So What Exactly is a Model View Controller? . . . . . . . . . . . . . 18

    MVC in PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    [email protected] Free To Ask Question You May Have

    Model View Controller (PHP)

    Rz RaselChapter - 02Page - 17

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    18/87

    Understanding the Model View Controller (MVC)

    As a computer science student, one of the rst things youll learn is the model-view-control -ler, or MVC. MVC is a widely used software architecture pattern that informs the design ofsome of your favorite software applications. Now well take a look at the MVC pattern in somemore 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 movementhas been a huge success, and the counterculture revolution is in full swing. More importantlyfor us, computer science has now established itself as a legitimate eld, not just the eccentrichobby of people with huge glasses and bigger beards. Some of the brightest minds in engi-neering and mathematics are collaborating in research labs at Stanford, Berkeley and thedozens 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 theLearning Research Group (LRG) of Xerox PARC in Palo Alto, California (the current home ofApple). These programmers are Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, and ScottWallace, among others. Together, they help create a programming language they call Small-talk. Its already been a few years since the development of the C language at Bell Labs; thereare already some software design standards in place. However, the invention of the Smalltalkprogramming language would affect virtually all these standards, and set the tone for the fu-ture of programming.

    It was from this language that the Model-View-Controller pattern rst emerged. Ted Kaehler isusually given credit for its development in 1978 in a paper titled A note on DynaBook require-ments, though his rst name for it was Thing-Model-View-Set. The aim of this MVC patternwas 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 rm understanding of MVC bythe time were done.

    What you should know for now is that MVC described the way a user could interact with a com-puter 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 MVCpattern,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 applica-tions interact with a user.

    This web page is a perfect example of the MVCstructure. Here, the HTML structure of thisweb page is the model, the CSS stylesheets that control its appearance are the View, and thebrowser 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 actualdata 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 .

    View:The view is a visual representation of the model. The view informs the way data struc-

    Model View Controller (PHP)

    Rz RaselChapter - 02Page - 18

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    19/87

    tured in the model will be made visible to the user. For example, the HTML may hold thetext, but the colors, font size and font style information is actually held by independent CSSstylesheets i.e. the view.

    Controller:A controller is the environment that bridges the divide between the user and thesystem. 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:

    USER MODEL

    CONTROLLER

    VIEW

    Heres a crude analogy: the muscles, bones and organs in your body are the model that holdseverything vital. The skin, hair, etc. are the view that controls the outward representationof the muscles and bones (the model). Your senses are the controller that helps the modelinteract 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 MVCin a Ruby on Rails or Django project.However, it is also used in some PHP web frameworks, though the implementation isnt nearlyalways uniform or in strict accordance with the theoretical foundation of MVCas laid down byTed Kaehler.

    CakePHP, which is one of the most popular PHP frameworks, uses an interpretation of theRuby on Rails MVC pattern. If you download a copy of the framework, youll see the followingdirectory structure in/app/:

    Model View Controller (PHP)

    Rz RaselChapter - 02Page - 19

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    20/87

    ..

    Cong

    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/:

    Model View Controller (PHP)

    Rz RaselChapter - 02Page - 20

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    21/87

    ..

    Component

    AppController.php

    PagesController.php

    Heres the MVC in CodeIgniter, another very popular PHP framework:

    ..

    cache

    cong

    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 themodel can interact with each other. In a pure MVC, all interactions must be handled by thecontroller alone. Most frameworks CakePHP included tend to treat the View as little morethan a CSS template that controls the way the web page/app looks. The MVC approach is typi-cally muddled in most PHP frameworks, both because of a poor translation of the Ruby on Railsand other similar frameworks.

    MVCis an abstract, theoretical topic that can be difcult to grasp for beginners. You can learn

    more about it in this course on PHP programming from scratch.

    [email protected] 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 TOHEAR.

    Feel Free To Send More Feedback Or Question You May Have.z

    Model View Controller (PHP)

    Rz RaselChapter - 02Page - 21

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    22/87

    03CONTENTS

    THE VIEW GETS ITS OWN DATA FROM THE MODEL

    Abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    MVC - Model View Confusion . . . . . . . . . . . . . . . . . . . . 23

    The view is more than a template . . . . . . . . . . . . . . . . . . 23

    Example 1 PHP Code . . . . . . . . . . . . . . . . . . . . . . . . 24

    Example 2 PHP Code . . . . . . . . . . . . . . . . . . . . . . . . 24

    Binding logic is problematic . . . . . . . . . . . . . . . . . . . . . 24

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

    When the view really needs the model . . . . . . . . . . . . . . . 25

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

    Better reusability . . . . . . . . . . . . . . . . . . . . . . . . . 26

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    [email protected] Free To Ask Question You May Have

    Model View Controller (PHP)

    Rz RaselChapter - 03Page - 22

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    23/87

    Abstract

    MVC is a common subject in the PHP community at the moment. There are a large body ofarticles, tutorials and code examples on the subject. Most of which deviate from the traditionalapproach to MVC and subscribe to an approach closer to MVP. Very few of these follow theMVC 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 ownMVC framework. Its a great learning exercise. The problem however, is the information whichis available to PHP developers. Much of it is poorly written, a great deal is fairly old fashionedand teaches bad practices. The majority of MVC related articles go off on tangents about suchtopics as the merits of DataMapper vs ActiveRecord, template systems, directory structures,how to do form processing and validation and other irrelevant implementation details. The big-gest problem, however, is that despite the inclusion of all this unrelated information they stillalmost all get the basics wrong.

    In MVC the view should access the model directly. This something which I have to argue a lotand 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 beno interaction between models and views: all the logic is handled by controllers.

    This is wrong. It species this nowhere in MVC. In fact, it states the exact opposite. Lets takea 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. Thecontroller may (in some implementations) issue a general instruction to the view to renderitself. In others, the view is automatically notied by the model of changes in state (Observ-

    er) 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 theHTML, 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 viewseem wrong, harking back to the days of mixing HTML and PHP. Dont get me wrong Im notgoing 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 themodels job it presents yet another hurdle. When the controller is doing the job of a model

    Model View Controller (PHP)

    Rz RaselChapter - 03Page - 23

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    24/87

    anyway, as in most PHP MVC frameworks, there is no model for the view to access! This hasto be done by the controller.

    Because of these fundamental problems, the only solution is to make the controller act as amediator. Generally by querying the model and passing the result to the view.

    Example 1 PHP Code

    $user = $this->model->user->ndById($id);$this->template->assign(rstname, $user[rstName]);$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 dataaccess layer) to the template:

    Example 2 PHP Code

    $user = $this->model->user->ndById($id);$this->template->assign(user, $user);

    While the latter is certainly an improvement, it merely makes the problem slightly less notice-able: binding logic.

    This puts extra work into the controller: Binding variables to the template. Controllers are notdesigned 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 termsof reusability and maintainability. Viewsare intended to be reused. In the examples above

    Im showing some basic user information. The template here may well (and, because the tem-plate 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 rst problem, then, is repeated code. The binding logic needs to be written in each andevery 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 difcult to trackdown.

    What if there are two users being represented in the view? Both of them have surnames andrstnames. The view now needs to reference rstname1 and rstname2 How can this bekept consistent across controllersand views? It cant. This all causes confusion for anyoneelse looking at the code. Isnt it better to prevent this in the rst place?

    Model View Controller (PHP)

    Rz RaselChapter - 03Page - 24

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    25/87

    In a similar vein, its possible for the controllers to be inconsistent. Because this logic evenexists, it removes any contract between the view and the model. This means address1 in theview doesnt really represent anything. It can be anything. Theres nothing to stop the control-ler sending the wrong data.

    For example, in one job I worked on a site with a similar set up. The requirements changedalong 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 devel-oper, he had to spend time working out why the address was showing on the new page andnot on the old one. The controller now inadvertently contained display logic: it was telling theview not to show the address. Again, prevention here is better than cure.

    Performance should be the nal consideration. The binding logic creates more code. Althoughcode cleanliness/reusability/maintainability shouldnt be sacriced for performance, in thiscase 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 be-come 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->nd($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 thiscode is reusable. Even though it will be the same for any paginated data. The only thing thatwill 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 andbusiness 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 havethe view read it. This way the view is agnostic about the state of the model (which page itson) 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 thelimit/offset (Details which are only relevant to how the data is going to be displayed when itspaginated) can be moved to the view. The view will call $user->nd() and $user->count()with the relevant parameters. The controller is doing less and the view is doing more. This

    Model View Controller (PHP)

    Rz RaselChapter - 03Page - 25

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    26/87

    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 bymultiple views. It may be useful for multiple views to use the same data. For example, havinga second view which used the paginated data and created some aggregated statistics aboutthe data displayed on the current page. This would need to be in sync with the rst view and

    always use the same data set. By storing the state in the model rather than the view, the pagecan be changed and both views will reect the changes. This reduces repeated code and addsexibility while improving separation of concerns.

    The View always has a contract with a model. Whether its a primitive array or a complex ob-ject, the view requires specic information. This is naturally unavoidable. By using the Modeldirectly, this contract is immediately fullled. If primitives are passed to the view, it has noway of knowing whether this contract is fullled until it breaks. Even if the result is a set ofobjects, the view cannot know whether the set is correct (because its likely a primitive arraycontaining objects) until it tries to use an object. By using the Model, the view can check thiscontract is fullled as the model is assigned to it, preferrably in its constructor.

    Even ignoring this, and assuming your controlleralways passes a valid data set you still losere-usability. The biggest issue with the controller as a mediatorapproach is that all thedata fetching logic (the calls to the model) has to be done in every single controller using theview, causing repeated code and therefore reduced reusability. In the pagination example, allthe calculations need to be repeated in each controller that uses the view. As an applicationdeveloper, each time you want to use pagination, would you rather pass a single variable tothe model which sets the page and does everything for you or fetch the records, work out thetotal number of pages then pass the result to the view?

    And pagination is a trivial example. In the real world, that controllerlogic is liable to change.If its repeated, it needs to be updated in every controller. By creating the reusability andseparation of concerns suggested by MVC the code doesnt need repeated and changes to themodelwill automatically be reected in any viewwithout 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 logicin the modeland all the display logic in the view. All the controller should be doing isgetting these talking. The less the controller is doing the better. Less controller code meansmore reusable code.

    Better reusability

    With all this theorising, it would certainly be worthwhile to include a basic real world exampleof why views are more than templates. I believe templates are worthwhile but they do notconstitute a View. Much in the same way the model layer is more than data access, the viewis more than a template.

    To demonstrate, heres a simple scenario: Show a list of users which can be ltered by search-ing for their name.

    Some example controller code. This will now be as minimal as possible.

    PHP Code

    class UserListController

    Model View Controller (PHP)

    Rz RaselChapter - 03Page - 26

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    27/87

    {

    private $model;public function __construct(UserListModel $model){

    $this->model = $model;}

    public function search($criteria)

    {$this->model->lterByName($critiera);

    }

    }

    Clean, empty controller code. Absent of both the views display logic and the models domainlogic. One thing to note here is that the controller does not require access to its view, only themodel. This is because in MVC, the only reason a controller needs access to the view is forthe observer pattern: to inform the view to refresh from the model. In PHP this is a non-issuebecause 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 lterByName($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 whichhas been searched for. In most pseudo-MVC frameworks the model has no state, the state isretained 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 ar-chitecture has developed.

    The view then fetches the data from its model. In this example the usage of a basic templatesystem has been assumed:

    PHP Code

    class UserListView

    Model View Controller (PHP)

    Rz RaselChapter - 03Page - 27

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    28/87

    {

    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 asthe model supplies a list of users the controller is agnostic about where they come from or anyknowledge about what them at all. This promotes robust code by making each component (themodel, viewand controller) entirely interchangeable. This is possible because it enforcesthe strict separation of concerns that MVC strives for. The controllerhas no knowledge of howthe view works. From an OOP perspective this is ideal as there is complete encapsulation. Theviewcan be substituted and it will never break the controller, the controller can be substitutedand it will never break the view.

    However, the goal here is reusability. Is the logic behind a listing a set of users any differentto listing a set of blogs, albums, products, etc? No, so why cant that logic be reused? A fewsimple amends and it can:

    Firstly, some interfaces are dened 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;}

    Model View Controller (PHP)

    Rz RaselChapter - 03Page - 28

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    29/87

    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 specic model. Because of the very strict separation of concernswhich is achieved by the view getting its own data from the model rather than being fed it bythe controller, the controller code is reusable. And so is the view:

    PHP Code

    Model View Controller (PHP)

    Rz RaselChapter - 03Page - 29

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    30/87

    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 specic model. The view does not care where its data comes from orwhat the data is. But theres more. Any of the three components can be substititued and re-used. The controller can be changed where needed. The view can be substituted for one whichdoesnt use a template engine while reusing the controller and model. Another controller canbe 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 iscorrect or best practice. Not everything you read is entirely accurate. Without valid reason-ing, a programming practice, regardless of its popularity is not always a good practice. Takesingletons as a perfect example. Something many articles seem to miss. They tell you howbut not why.

    [email protected] YOUVE GOT SUGGESTIONS FOR IMPROVEMENTS ID LOVE TO SEE. DONT HESI-TATE.

    IF ITS HELP YOU PLEASE LEAVE A COMMENT AND LET ME KNOW. ID LOVE TOHEAR.

    FEEL FREE TO SEND MORE FEEDBACK OR QUESTION YOU MAY HAVE.z

    Model View Controller (PHP)

    Rz RaselChapter - 03Page - 30

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    31/87

    04CONTENTS

    MVC MODELS ARE NOT DOMAIN MODELS

    Flexibility vs Reusability . . . . . . . . . . . . . . . . . . . . . . 32

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    Terminology: ViewModels View Helpers, Models . . . . . . . . . . . 35

    What is a view helper? . . . . . . . . . . . . . . . . . . . . . . . 35

    An Implementation . . . . . . . . . . . . . . . . . . . . . . . . 35

    The Template . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    The View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    The ViewModel . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

    PHP Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    A small disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . 41

    [email protected] Free To Ask Question You May Have

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 31

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    32/87

    Flexibility vs Reusability

    To completely contradict part, while correct, its not the solution either. It is certainly an im-provement over fat controllers. However, was it much of an improvement? Isnt reusabilityreduced by giving the view access to the model?

    In any software design, there is always a trade off between exibility and reusability. On one

    hand a very exible system could be created where the client code has to specify pretty mucheverything. For example, in terms of views, passing a model object to the template and havethe template do everything: query the model, process the data and generate the HTML. Thisis incredibly exible: there are no limitations on what it can do. However, its not reusable atall. 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 thesystem the view, with minimal to no conguration could take any model which meets theseassumptions. Of course things break when requirements change or it needs to do somethingeven slightly different. It encourages a copy, paste and modify slightly mentality, which is ofcourse, 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 growbeyond its initial scope.

    The last point here is a hard one to judge. Would it be worthwhile to deploy a template engineor full MVC stack for a 5 page brochure site? how about 10 page? What if that 5 page site grewinto a 30 page site within a year then the client wanted latest news added to each page. If thesystem 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 logle? Trying to be a soothsayer and second guess what clients (who are notoriously ckle be-ings) 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 makethings easier in the long run.

    It argues that in MVC the view should have direct access to the model. It contains some basiccode examples to demonstrate the benets. The solution is for demonstration only. As such itis neither complete, nor perfect. However, the general idea of the view calling functions on themodel 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 rm contract betweenthe model and the view. This reduces reusability of the view because the model now needs tohave a very specic interface.

    Reusable ListView class:

    PHP Code

    class ListView

    {

    private $model;private $template;

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 32

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    33/87

    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 moreimportantly, the view requires the model to implement the Searchable interface . The result ofthis is that the view is only usable by certain models. But what about other views which mayneed 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 modied to implement the Searchable interface? Ideally themodel should be reusable without modication. Otherwise each model which can used be theview needs to be modied.

    The problem arises because each view requires models to implement specic interfaces. In thereal world, a model is going to be used by any number of views. The model should not be mod-ied in order to allow each potential view to use it. It causes clutter in the model and causesharm 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 meanDomain models. That is, the model which encompasses the problem domain, dealing withreal-world concepts. Blogs, users, products, etc. In MVC, while the Model does contain thesethings, 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 $lter;public function __construct(Searchable $model, Template $template){

    $this->model = $model;

    $this->template = $template;}public function output(){

    $this->template->assign(data, $this->model->getData($lter));return $template->output();

    }}//controller code

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 33

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    34/87

    $this->view->lter = rstname = . $name . ;

    Here, the state has been moved into the view. The view contains the search criteria ratherthan the model. Is this the answer?

    No, For a start, Display logic has been reintroduced into the controller. More importantlythough, now any model which uses the view requires a very specic getData implementa-

    tion. This severely reduces reusability to only models which follow this specication.

    Extending this idea into more complex views means more specic calls to a model, whichmeans its less reusable views. To use a totally different model would be programmatically try-ing 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, $lter){

    //...}

    }

    class ViewA{

    //...public function output(){

    $result = $this->model->getData($this->order, $this->limit, $this->lter);//...

    }

    }

    Meanwhile, developer B develops a model and a view which work together:

    PHP Code

    class ModelB{

    public function getData($rstname){

    //...}

    }

    class ViewB{

    //...public function output(){

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

    }

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 34

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    35/87

    Now theres a situation where ModelB cannot be used with ViewA and ModelA cannot be usedwith 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 dan-gerous. This potentially introduces unrelated concepts into models (e.g. ModelA may not beanything to do with users).

    Alternatively, the views could be modied, but again, theres no clean way to do it. Either theyneed to extended and have the entire output() method re-written, or have some hacky logicin the view deciding which method to call in the model.

    The ideal scenario is that both the model and view can be reused without modication. Thisallows for ultimate reusability and a very large amount of exibility

    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 Mis-understood and Unappreciated. Although he accurately points out the misunderstanding ofModels, the problem is peoples preconceptions of models. He re-enforces this by discussingdomain models in terms of MVC Models. They are not the same thing. The MVC Model doesencapsulate domain models, but for the purpose of MVC, although you can write a MVC Modelwhich 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 interactionbetween the model and the view. This is actually what MVC refers to as The model and nota separate component. However, because the term Model has evolved to have a specicmeaning 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 modularand facilitates component reuse. Multiple clients, such as controllers and views, may leveragethe 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 theViewModel denes only how a model interacts with a specic view. This xes the problem ofeither coding a view around a model, or coding a model to t a view. It is considered part ofthe 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 dem-onstration. How this works is not relevant and is far beyond the scope of this article. Oftenthe template itself will not be reused: It is tied directly to the domain model. For example, itknows what elds a User object has. It has direct access to its ViewModel, this allows it toread what it needs, eliminating the need for binding logic in the view.

    The View

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 35

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    36/87

    This contains all the display logic for interacting with the template and is the only place thetemplate is interacted with directly. Most of the time it will simply assign the helper to thetemplate. When a View is dened it should also dene an interface for the helper which it isgoing to use. It does not interact with models directly. It uses a ViewModel to get any data itneeds from the model.

    The ViewModel

    This implements the specic interface dened alongside the view. E.g. FormView will require aViewModel which implements the interface FormViewModel. The ViewModels job is to link themodel layer to the view layer and store the state of the application. For instance it will storethings 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 couldbe 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 rst argument. In this case, the ViewModel must implement theSearchable 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);}

    }

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 36

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    37/87

    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 meth-ods which exist for the sole purpose of specic views accessing data. However this can beresolved:

    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->ndByName($this->searchName);

    }}class UserModel{

    private $db;public function __construct(Db $db){

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 37

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    38/87

    $this->db = $db;}public function ndByName($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 ViewModelwill always be incredibly minimalist. It will never contain complex logic, database access, itsa simple wrapper to enable view to access its data. The domain model now has a generic

    ndByName method which can be used by any ViewModel. The application state (what hasbeen searched for) remains in the ViewModel while the domain state (the data about users) isencapsulated in the domain model.

    The view layer is now made up of 3 parts. For people used to templates as views this willlikely seem daunting. However, take a look at the controller. Its entirely minimalist and re-usable which is far superior to the mess of fat controllers which are required by the majorframeworks. Minimal controllers are good controllers.

    To test the reusability, the view could be reused with minimal conguration by another modelwith 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->ndByCodeNumber($this->searchCode);

    }

    }

    class ProductModel{

    private $db;public function __construct(Db $db){

    $this->db = $db;}

    public function ndByCodeNumber($code){

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 38

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    39/87

    //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 re-

    used. 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->ndAll();}

    }

    In this case, a controller would not even be required! The view would get its data from theViewModel and it wouldnt even matter that the controller didnt exist.

    With minimal code, a lot different fairly substantial variations are possible due to having bothhigh exibility and high reusability.

    Heres one more example using something slightly more complex. Like part 1 pagination willbe used again, its simple and commonplace enough that everyone understands it, yet its not-

    trivial enough to provide a worthwhile demonstration.

    PHP Code

    interface Pageable{

    //Get the records using limit and offsetpublic function nd($limit, $offset);//The number of records which will be shown on each pagepublic function getRecordsPerPage();//The page currently being shownpublic 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){

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 39

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    40/87

    $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->nd($perPage, ($pageNo-1)*$perPage);$totalRecords = $this->model->getTotalResults();$totalPages = ceil($totalRecords/$perPage);for($i = 1; $i 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 templatesystem works is irrelevant. It is included for demonstration purposes only. The ViewModel isthen dened 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 nd($limit, $offset){

    return $this->user->ndByName($this->searchName, $limit, $offset);}public function getRecordsPerPage(){

    //Lets show 20 users per page.return 20;

    }public function getCurrentPage(){

    return $this->page;}public function getTotalResults(){

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 40

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    41/87

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

    }public function setPage($page){

    $this->page = $page;}

    }

    Of course the same could be done with a different model: Blogs, products, etc. The controlleris 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 viewinteracts 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 demonstratesthe benets of separating the view elements well and should provide a solid base for anyonewishing 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 notbe done in the best way (Should the variables being replaced in the template be put in thehelper instead of the view). However, using practical examples, I believe Ive successfullyargued the case for splitting views into 3 parts. It is more code to set up, but the power andreusability 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,

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 41

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    42/87

    the new keyword instead of factories/dependency injection, insecure code which is subjectto SQL injection and things which are considered bad practice. All this is for the sake of sim-plicity: The article is teaching the idea of views/view helpers not other best practices. Becauseof this, please dont take code which is outside the scope of the article and use it without un-derstanding the implications behind it.

    [email protected]

    IF YOUVE GOT SUGGESTIONS FOR IMPROVEMENTS ID LOVE TO SEE. DONT HESI-TATE.

    IF ITS HELP YOU PLEASE LEAVE A COMMENT AND LET ME KNOW. ID LOVE TOHEAR.

    FEEL FREE TO SEND MORE FEEDBACK OR QUESTION YOU MAY HAVE.z

    Model View Controller (PHP)

    Rz RaselChapter - 04Page - 42

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    43/87

    05CONTENTS

    PHP MVC FRAMEWORK BASIC INTRODUCTION

    Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

    What is PHP MVC Framework? . . . . . . . . . . . . . . . . . . . 44

    How to implement PHP MVC Framework? . . . . . . . . . . . . . . 44

    Model in PHP MVC Framework . . . . . . . . . . . . . . . . . . . 44

    Code snippet (Book Class) . . . . . . . . . . . . . . . . . . . . . 44

    Code snippet (Model Class) . . . . . . . . . . . . . . . . . . . . . 45

    Controller in PHP MVC Framework . . . . . . . . . . . . . . . . . . 45

    Code snippet (controller class) . . . . . . . . . . . . . . . . . . . 45

    View in PHP MVC Framework . . . . . . . . . . . . . . . . . . . . 46

    Code snippet . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

    Codes All Together . . . . . . . . . . . . . . . . . . . . . . . . . 47

    [email protected] Free To Ask Question You May Have

    Model View Controller (PHP)

    Rz RaselChapter - 05Page - 43

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    44/87

    Introduction

    The Model View Controllerpattern is the latest application development framework for devel-oping desktop, mobile, and web applications. It is extremely useful in large scale applicationsbecause in MVC, different parts (views, business logic and storage) of a system are developedseparately resulting in loosely coupled modular application. As a result, maintenance, ex-ibility, and scalability of a system increases andcode becomes shorter and easier to read. A

    lot of PHP frameworks are based on MVC patterns which already exist, but even using thesesolutions 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 modelsare developed separately, enabling the designers to work with the views without any concernwith the data and its handling; same goes for a programmer whose main focus is on develop-ing 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 descriptionof model, view and controller with the example of Book Selection application in whicha user selects an entry of book from a combo-box and selecting the value, which results in adetailed description of the book. For simplicity, code is maintained in one le.

    Model in PHP MVC Framework

    In PHP MVC Framework, the model is responsible for managing the data that involves the stor-age and retrieval of entities like the user or a product order from the databaseor storedarrays. The model is a part of application that involves processing the data required by an ap-plication. The model part is unaware of the business logicand its corresponding view.

    In the example of a Book Selection model, part of PHP MVC framework is represented bytwo classes Book and Model. The Book is an entity class used to keep the books data. Themodel class is used to store and retrieve the books data.

    Code snippet (Book Class)

    Model View Controller (PHP)

    Rz RaselChapter - 05Page - 44

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    45/87

    Code snippet (Model Class)

    In the above code snippets of PHP MVC framework example, the Book class is used to keepthe data of a books name, version and publishing year. The model class stores the booksdata in the form of associative array with a method to return all the books data and a singlebook ltered by the name attribute with addition of the text property that has the applica-

    tion name.

    Controller in PHP MVC Framework

    In PHP MVC framework, the controller takes an input from user as a request, processes andanalyzes this input, initializes and invokes the model, takes the model response and sendsit back to the respected view.So controller is a part of application that involves the logicalprocesses of the applicationalso called the business logic. It acts as a middle layer for viewsand models.

    In the example of a Book Selection controller, part of PHP MVC framework is represented byone class Controller. This class instantiates the model class and call the methods to retrievethe books information based on the request nature.

    Code snippet (controller class)

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    46/87

    $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 . $this->model->text . ;}

    }

    ?>

    In the above code snippet of PHP MVC framework example, the controller class instantiatesthe model using its constructor. Different methods of model are called based on the requestnature. When the page is loaded for the rst time, a getBookList method of model is calledto return all book details and getBook is called when a GET request is made, which results ina specic book detail based on the requested book name. The output function of a controlleris 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 logicused to present datafrom the model to the user.It passes the user input to a controller using control events. Inshort, 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 asubmit button. It instantiates the Model and Controller classes to call the invoke methodof a controller and populates the combo-box with the retrieved data.

    Code snippet

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    47/87

    ?>

    In the above code snippet, the output method of controller is called to generate the name ofthe application with the html heading tag. Next,the invoke method is called to retrieve thebooks information. A combo-box is lled 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 sameview, which displays details of selected book as output HTML page.

    Codes All Together

    The directories structure:+rz-mvc index.php

    rz-mvc index.php

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    48/87

    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];

    }}?>

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    49/87

    }}?>

    [email protected] YOUVE GOT SUGGESTIONS FOR IMPROVEMENTS ID LOVE TO SEE. DONT HESI-

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

    Model View Controller (PHP)

    Rz RaselChapter - 05Page - 49

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    50/87

    06CONTENTS

    MVC LITTLE HISTORY AND WEB APPLICATIONS

    MVC little history . . . . . . . . . . . . . . . . . . . . . . . . . 51

    MVC for Web Applications . . . . . . . . . . . . . . . . . . . . . 51

    Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    Lets See an Example . . . . . . . . . . . . . . . . . . . . . . . 52

    What are the Advantages? . . . . . . . . . . . . . . . . . . . . . 53

    Ok, but Why a Framework? . . . . . . . . . . . . . . . . . . . . . 54

    Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

    Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

    [email protected] Free To Ask Question You May Have

    Model View Controller (PHP)

    Rz RaselChapter - 06Page - 50

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    51/87

    MVC little history

    Model-View-Controller (MVC)is probably one of the most quoted patterns in the web program-ming world in recent years. Anyone currently working in anything related to web applicationdevelopment will have heard or read the acronym hundreds of times. Today, well clarify whatMVC means, and why it has become so popular.

    MVC is not a design pattern, it is an Architectural pattern that describes a way to structureour application and the responsibilities and interactions for each part in that structure.

    It was rst described in 1979 and, obviously, the context was a little bit different. The conceptof web application did not exist. Tim Berners Lee sowed the seeds of World Wide Web in theearly nineties and changed the world forever. The pattern we use today for web developmentis an adaptation of the original pattern.

    The wild popularization of this structure for web applications is due to its inclusion in two de-velopment frameworks that have become immensely popular: Struts and Ruby on Rails. Thesetwo 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 thefollowing responsibilities clearly separated in our application:

    ModelHandel data and business logic

    ViewPresent data to the user in any suppoed

    format and layout

    ControllerReceive user requests and call appropriateresources to carry them out

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

    Model View Controller (PHP)

    Rz RaselChapter - 06Page - 51

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    52/87

    Controller

    The Controller manages the user requests (received as HTTP GET or POST requests when theuser clicks on GUI elements to perform actions). Its main function is to call and coordinate thenecessary resources/objects needed to perform the user action. Usually the controller will callthe 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 theapplication manages. In any software system, everything is modeled as data that we handle ina certain way. What is a user, a message or a book for an application? Only data that must behandled according to specic rules (date can not be in the future, e-mail must have a specicformat, name cannot be more than x characters long, etc).

    The model gives the controller a data representation of whatever the user requested (a mes-sage, a list of books, a photo album, etc). This data model will be the same no matter how wemay 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 tothe problem we are dealing with (a forum, a shop, a bank, etc). The controller contains a moreinternal-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 betemplates where that data is lled. There may be several different views and the controllerhas to decide which one to use.

    A web application is usually composed of a set of controllers, models and views. The controllermay be structured as a main controller that receives all requests and calls specic controllersthat handles actions for each case.

    Lets See an Example

    Suppose were developing an online book store. The user can perform actions such as: viewbooks, register, buy, add items to current order, create or delete books (if he is an adminis-trator, etc.). Lets see what happens when the user clicks on the fantasy category to view thetitles 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 examplebook_model.php, handling data and logic related to the items in the shop. Finally we will havea series of views to present, for example, a list of books, a page to edit books, etc.

    The following gure shows how the user request to view the fantasy books list is handled:

    Model View Controller (PHP)

    Rz RaselChapter - 06Page - 52

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    53/87

    1

    2

    3

    4

    56

    MODEL

    USER

    VIEW

    CONTROLLER7

    The controller (books_controller.php) receives the user request as an HTTP GET or POST re-

    quest (we can also have a central controller, for example index.php receiving it and then call-ing 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 isstored), apply lters 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 requestcame from a mobile phone, a view for mobile phones will be used, if the user has a particularskin 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 (theinterface with the user) and application logic.

    Support for different types of users using different types of devices is a common problem thesedays. The interface presented must be different if the request came from a desktop computeror from a cell phone. The model returns exactly the same data, the only difference is that thecontroller will choose a different view to render them (we can think of a different template).

    Model View Controller (PHP)

    Rz RaselChapter - 06Page - 53

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    54/87

    Apart from isolating the view from the business logic, the M-V-C separation reduces the com-plexity when designing large applications. The code is much more structured and thereforeeasier maintain, test and reuse.

    Ok, but Why a Framework?

    When you use a framework, the basic structure for MVC is already prepared and you justhave to extend that structure, placing your les in the appropriate directory, to comply withthe Model-View-Controllerpattern. Also you get a lot of functionality already written andthoroughly tested.

    Take cakePHP as an example MVC framework. Once you have it installed, youll see three maindirectories:

    app/ cake/ vendors/

    The app folder is where you place your les. It is your place to develop your part of the ap-plication.

    The cake folder is where cakePHP has its les and where they have developed their part (mainframework functionality).

    The vendors folder is for third-party PHP libraries if needed.

    Your working place (app directory) has the following structure:

    app/ cong/ controllers/

    locale/ models/ plugins/ tests/ tmp/ vendors/ views/ webroot/

    Now you have to put your controllers in the controllers directory, your models in the modelsdirectory 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 alot 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, viewand controllercomponents andcomment on the benets of using an MVCframework. The code is oversimplied and not suit-able for real applications.

    Model View Controller (PHP)

    Rz RaselChapter - 06Page - 54

  • 8/9/2019 PHP Model View Controller 1st Edition Full

    55/87

    Remember we had a book store and a curious user who wants to see the complete list of booksin the fantasy category. We said that the controller will be the one receiving the request andcoordinating 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 isthe 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:

    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 otherfunctions to perform other book-related actions (add a new book, delete a book, etc).

    The framework provides a lot of th