PHP5 MVC Tutorial
ANew     OnLine phpApplications    GNU-GPL License    PHP Certification Certificate


Welcome to PHP5Anew MVC (Model,View,Control) tutorial,


Application Code        Demo Sample MVC Simplified


In an effort to present enterprise application architectural programming to those individuals with no prior experience simplicity thru the introduction of design patterns will help to form a better understanding of key concepts and components vital to this type of application development and programming. MVC is the idea that you have three different pieces that work in unison to form a complex application. The ideas behind MVC pattern are quite simple and extremely flexible. The idea is that you have a single controller(ie. index.php) that controls how applications are launched within the framework based on arguments in the request. This usually includes, at a minimum, an argument defining which model to invoke, an event and the usual GET arguments. From there the controller validates the request(authentication, valid model, request sanitization, etc.) and runs the request event.

The MVC (Model,View,Controller) is the illustration of one design pattern although there are several different types of patterns(Composite, Observer, Facade, Factory, Decorator, Builder). Although each pattern handles a different design issue, one feature is common to them all. After the work to develope and implement the pattern is finished, the code to actually use it is very simple and flexible. Patterns allow developers and software designers to share complex ideas with a single term. The same design pattern can be a solution in very different types of software. Often you'll see design patterns incorporated into a large framework. Their reusable ideas. The MVC design pattern is defined in different colors for clarity although the actual visiable pages you will see are the controller.php(request.php) page below in the simplified example code &  view.phtml (yourApplication_results.phtml) page below in the simplified example code.

In the real world several files for each part of the design pattern could be part of the application. If you have 3 different databases to login to these would be 3 seperate model.phpm files each with a unique name maintaining the same extension. Likewise if you have 5 different controller.php files these would also have unique names maintaining the same extension. The view.phtml(template) file could also be one of several different application templates with a unique name maintaining the same extension depending on the controller.php request. To avoid confusion its recommended that the MVC files each have seperate file extensions(i.e. model.phpm, view.phtml, controller.php)

Seperation yields interchangeability. By keeping three components seperate, yet having them talk to one another in a consistant manner, you can swap any component out should you need to. For example if you need to rebuild your Web applicaton to to work on PDAs instead of web browsers you can swap out your View component for one that renders content especially for the PDA rather than the Web browser. If you need to accept data via voice input rather than mouse clicks, you can swap out your controller component for one that uses VoiceXML. Debugging to catch hard-to-trace bugs after release are made immeasurably simpler if there is a seperation of logic in sensible places. Its much better to have lots of small components that talk to each other than just a handful of huge, unwielding files filled to the brim with code. A complex software architecture can be made a great deal simpler by seperating components in this way.

In the creation of the frameworks for the MVC there are two other important critical components. The PEAR DB Libary and a templates engine (Smarty Template Engine). PHP5 introduced a new class, Exception, which is almost a drop in replacement for PEAR_Error. However, PEAR_Error has a few extra features that makes it a more robust solution then Exception. As a result, this framework and foundation classes will use the PEAR_Error class for error handling. I will use Exception, however to throw errors from the constructors as they cannot return errors.

Smarty ia a package for PHP that allows developers to easily prepare output for a template and then leave the template to display it in what ever way it sees fit. Smarty is unique in that it provides not just simple 'dump value' methodlogy, but also allows loops, conditionals, and the traversing of multidemensional arrays. It replicates all the traditional simple PHP methods used in native PHP templating without using PHP at all. Smarty is extremely fast. It actually creats native PHP from the template. The native PHP is the cached, such that if the template is not changed with subsequent requests, the templates itself does not have to be translated into PHP again. It is simply pulled straight from the cache and executed.


Overview Of  Classes Design Goals


The concepts of classes and objects and the ways you can leverage ideas in the development of software are the fundemental ideas behind object-oriented programming. This is in a sense, the opposite of procedural programming, which is programming using functions and global data structures. An object-oriented approach gives some big benifits over procedural programming and with the new implementation of OO support in PHP5, some large performance boost as well.

Because OO approach forces you to think about how code is organiized, learning the structure of an existing application is much easier when you are new to the develoment team. In addition you have a framework to aide you in determining the approriate location for new functionality you might develop. A class can never have property values or state. Only objects can. An object is a concrete entity constructed using the blueprint provided by the class. Similarily, you have to instantiate an object from the class before you can interact with its properties or invoke its methods. Classes are manipulated at design time when you make changes to the methods or properties. Objects are manipulated at runtime when the values are assigned to their properties and their methods are invoked. The problem when to use the word classes and when to use the word object is something that often confuses those new to OOP. After an object is instantiated it it can be put to work implememnting the business requirements of the application. One of the main benifits of OOP is the ease with which you can translate individual business requirements into individual modules of code. Because an OO approach enables you to model your application based on real-world objects, you can identify a direct correlation between people, things, and concepts they represent, which helps you to quickly identify what code needs to be written and how different parts of the application need to interact.

A second benifit of OOP is the modularity of classes and code reuse. You frequently need the same types of data in different places in the same application. This is one of the biggest benifits of an OO approach-the opportunities for code reuse within a given application as well as across different projects. If you discover a bug in your class or you want to change or add the way that class functions, you only have one place to go. All the functionality of that class is contained in a single file. Any processes of the class are immediately effected by the changes to it. This feature can vastly simplify the search for bugs and make the addition of features a relatively painless task.

Overview Of  Foundation Classes Design Goals
  • Leverage Pear to quickly add functionality to foundation classes
  • Create small, reusable abstract foundation classes that will enable developers to quickly build applications within the framework
  • Document all foundation classes using PHPDocumentor tags
  • Prepend all classes and global variables with FR to avoid possible variable/class/function collisions
Classes Hierchy
  • FR_Object - Will provide basic functionality all objects need (logging, generic setFrom, toArray, etc.)
    • FR_Objet_DB - A thin layer to provide child classes a database connection along with other functions such classes might need
      • FR_Object_Web - A thin layer that provides session and user information for web based applications
        • FR_Module - The base class for all applications(aka "modules", "model", etc.)
          • FR_Auth - The base authentication class, which will allow for multiple authenitication mechanisms.
            • FR_Auth_User - An authentication class that will be used in modules that require a valid user is logged in.
              • FR_Auth_No - A dummy authentication class that will be used for modules that require no authentication
    • FR_Presenter - The base presentation class (aka "view") that will handle loading and displaying the applications after they have been ran.
    • FR_Presenter_Smarty - The presentation layer will include the ability to load different drivers. Smarty is template class that has built in caching.
    • FR_Presenter_Debug - A debugging presentation layer that developers can use to debug applications.
    • FR_Presenter_rest - A REST presentation layer that developers can use to output applications in XML
File System Layout


Although there is no particular classic scheme that dicates how you should have your file system arraigned. What we need to keep in mind is the approach of keeping things as simpilistic as possible. A basic file layout that will benifit your application without repetative cumbersome directories is illustrated below. The directory includes will contain all foundation classes inside and will also follow a specific pattern to make use of PHP's new _autoload() function. Another directory will be for modules. Each module will contain their own seperate configuration file(config.php), at least one module file(.php) and one tpl file. All modules will reside in modules directory (modules/)
  • /
    • config.php
    • index.php
    • includes
      • auth.php
      • auth/
        • no.php
        • user.php
      • module.php
      • object.php
      • object/
        • DB.php
      • presenter.php
      • presenter/
        • common.php
        • debug.php
        • smarty.php
      • Smarty/
    • modules/
      • example
        • config.php
        • example.php
        • tpl/
          • example.tpl
    • tpl/
      • default/
        • cache/
        • config/
        • templates/
        • templates_c/






MVC Pattern(Model, View, Controller) Illustrated In Technicolor
PHP5Anew.Com MVC Tutorial

Model.phpm: Programming PHP (Core Logic Of the Component)

(classes) should never contain HTML

This particular section is what we will consider the model in the MVC (model,veiw,controller) design pattern. The model.php handles the programming portion of php. It is the core logic of the component. The logical actual execution code of the application, php and database code that executes on the web server. There should never be any html code in this file. This file and its content is executed behind the scenes and is never visable since it is script. Generally speaking , it refers to the the suite of classes you have developed to handle the various processes involved in your applications behavior. It concerns itself with retrieving the data behind the output, as well as manipulating data as a resultof user input. It also connects directly to both the controller and the view. The controller supplies the model with its instructions; the view manipulates the data retrieved from the controller into a human-usable output.

Classes are a blue print for constructing an object. Using the construct known as a "class" allows you to establish the idea of an object and all its characteristics. In "OO" treminology, the characteristics of a class are known as its properties. Properties have a name and a value. Some allow their value to be changed , some do not. Some properties represent the state of an object. State refers to those characteristics that change because of certain events but are not neccessarily directly modified on their own. In an application that simulates performance , the class may have a property that that is not a value that can change on its own, but rather is a byproduct of the characteristics of that state. Classes are the "blueprints" for an object and the actual code that defines the the properties and and methods. A class is a unit of code, composed of variables and functions, which describe the characteristics and behaviors of all memembers of a set(note: An object oriented language must support polymorphism, which means different classes can have different behaviors for the same opperation(s) Polymorphism is more characteristic of behaviors then it is of objects). The characteristics of a class are known as its properties. Methods of classes are syntactiaclly equivalent to functions found in traditional procedural code. Just like functions methods can accept any number of parameters, each of any valid type. Some methods act on external data passed to them as parameters, but they can also act on the properties of their object, either using those properties to inform actions made by the method or to change the state of an object by modifying values.

PHP5Anew.Com MVC Tutorial

Controller.php: Processing Events of Application (User Interaction Of Application)

(control page) should never contain SQL queries or HTML

This particular section is what we will consider the contoller in the MVC (model,veiw,controller) design pattern. The controller.php handles all user interaction. It is the user interaction of the application including processing events. The menu event system and extensions such as the search module that sends user requests into the model for logical code execution, php and database code that executes on the web sever.This file can be considered as where the user input is administered & entered before being forwarded to model.phpm. The controller connects directly to the Model, to which it supplies the data or request in question. The Model then goes about fulfilling that request or storing that data as appropriate.

View.phtml: Template php.html (Presentation Rendering Logic)

(templates) should never contain SQL queries, and only very basic PHP(for/if/while)

This particular section is what we will consider the view.phtml in the MVC (model,veiw,controller) design pattern. The view.phtml handles all presentation rendering logic. The presentation of graphics or text of the application. It is the template that determines how the web page contenet is displayed once the model.phpm code is executed on the server. The View is at the user end of the application. It presents data from the model that the user has requested or information that the models considers that the user needs to know. The View also connects directly to the Model. The Model supplies data directly to the View for it to display in a manner appropriate to the display device in question. Arguably, the view also connects to the controller, in the sense that it provides the physical rendering of the necessary controls for the input to be made to your application in the first place.

The Infrastructure

The infrasrture is the fourth component to the MVC. The job of the infrastructure is to glue the model, view, and controller together. How this is done varies enormously from language to language. In my particular phpapplication assemble.php(page-template frame) consisting of a header.inc, top.php, side.php, body.php and footer.inc to maintain the php5-mvc application together. Along with PHP5 page.inc is used to display a homepage "home.php". page.inc-The Class Provides an easy and flexiable way to create your web site pages and can be viewed within the index.php included coded as a include in the "body.php".






Top


An example of what the code could look like is illustrated below:

{* This Application Code Is MVC Framework Simplified *}

< ?

require_once("config.phpm");
require_once("constants.phpm");
require_once("request.phpm");
require_once("constraints.phpm");
require_once("constraintfailure.phpm");


$strTemplateFile = "registration & login_results.phtml";

$displayHash = Array():

$objRequest = new request ( );
$objRequest ->SetRedirectOnConstantFailture(true);

$objConstraint = new constraint(CT_MINLENGHT, "3");
$objRequest ->AddConstraint("typeOfSearch",VERB_METHOD_GET, $objConstraint);
$objConstraint = new constraint(CT_MAXLENGHT, "12");
$objRequest ->AddConstraint("typeOfSearch",VERB_METHOD_GET, $objConstraint);
$objConstraint = new constraint(CT_PERMITTEDCHARACTERS,"ABCDEFGHIJKLMNOPQRSTUVWXYZ,abcdefghijklmnopqrstuvwxyz");
$objRequest ->AddConstraint("typeOfSearch",VERB_METHOD_GET, $objConstraint);

$objRequest = setConstraintFailtureDefaultRedirectTargetUrl("registration.phtml");
$objRequest ->TestConstraints( );

# If we have gotten this far tests have been passed - perform the search. $displayHash[RESULTS] = Array( );
$arSearch = array("WWW.YourWebSite.Com","WorldWideWeb");


for($i = 0, $i< = sizeof($arSearch) -1; $i++) {
if (!(strpos(trim(strtolower($arSearch[$i])), strtolower(trim($objRequest->GetParimeterValue("typeOfSearch"))))
 =  =  =  false))
   {
array_push($displayHash["RESULTS"], $arSearch[$i]);

       };
   };

require_once($strTemplateFile);
exit(0);
? >











Acknowledgements & Credits


Special Thanks to the Joker. Your help with the login script has been an essential part in moving forward with this project. Thank You!

Dan Rahmel author of Joomla Wrox ISBN: 978 - 0 -470 - 13394 - 1 A walk through of the process of creating extensions (modules, components, and plug-ins), including how best to use Ajax technologies, design patterns, incorporate source code and control lightweight Directory Access Protocol(LDAP).

Joe Stump  your tutorial's insight to what we can accomplish with a little motivation and the right direction.

Ed Lecky-Thompson, Howe Eide-Goodman Nowicki, Steven D. Nowicki, Alec Cove authors of Professional PHP5 ISBN: 0 - 7645 - 7282 - 2 for their help in expanding and leveraging the development skills we need as PHP developers by utalizing features of PHP5 and taking our software development beyond mere syntax and traditional development techniques.