mvc with php

9
FEATURES FEATURES May 2003 · PHP Architect · www.phparch.com 10 An Introduction to MVC Using PHP What is MVC? By now, you have probably heard the term MVC - an acronym for Model-View-Controller. You may also have heard that this design pattern is a good architecture for a web site. Just what MVC is, and how this concept can be applied in PHP, is what I hope to uncover in this arti- cle. MVC is an Object Oriented (OO) design pattern. A Model-View-Controller uses classes to organize Business Logic (where data is stored, who is authorized to manipulate it, and how the data is manipulated) con- tained in “Models”, Presentation Logic (how the data from the Models should be rendered) in “Views” and has an overall flow for the application within a “Controller”. I was amazed to find that the MVC pattern was devel- oped at Xerox Palo Alto Research Center (PARC) in the late seventies. In addition to the mouse and the con- cept of a windowed GUI, we also owe thanks to these creative folks for the Model-View-Controller! Why Use Design Patterns Anyway? A “Design Pattern” is a collection of objects, and rela- tionships between those objects, that has been devel- oped and tested to efficiently solve a particular class of problems. If the problem you are solving matches the problem solved by a design pattern, then you can get a significant head start on implementing your solution by adopting the design pattern. You will still need to customize the portions of the code for your system, but you will have a well tested, robust architecture in place as a base for what you code. There are many different design patterns to solve a variety of problems. The “bible” of design pattern information is the book titled “Design Patterns” by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (often called the “Gang of Four”). A good starting point for the investigation of PHP design pat- terns is the ::phpPatterns() site (http://www .phppatterns.com/ ). Why use MVC? Now that you have been primed with a high-level overview of the MVC, and understand that it is a design pattern, you may still wonder why you would want to use it with PHP. The reason is that the MVC pattern is An Introduction to MVC Using PHP By Jason E. Sweat Few design patterns are as 'tried and true' as the Model View Controller pattern (MVC). In this first part of a two part series, we'll go over the general philosophy of MVC and why it is useful; what resources are available to help the budding MVC coder; and we'll wrap things up with a little code to drive the concepts home. PHP Version: 4.0.6+ O/S: Any Additional Software: Smarty REQUIREMENTS

Upload: jewelbd

Post on 11-Apr-2015

12.757 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MVC with PHP

FEATURES

FEATURES

May 2003 · PHP Architect · www.phparch.com 10

An IIntroduction tto MMVCUsing PPHP

What is MVC?By now, you have probably heard the term MVC - anacronym for Model-View-Controller. You may also haveheard that this design pattern is a good architecture fora web site. Just what MVC is, and how this concept canbe applied in PHP, is what I hope to uncover in this arti-cle.

MVC is an Object Oriented (OO) design pattern. AModel-View-Controller uses classes to organize BusinessLogic (where data is stored, who is authorized tomanipulate it, and how the data is manipulated) con-tained in “Models”, Presentation Logic (how the datafrom the Models should be rendered) in “Views” andhas an overall flow for the application within a“Controller”.

I was amazed to find that the MVC pattern was devel-oped at Xerox Palo Alto Research Center (PARC) in thelate seventies. In addition to the mouse and the con-cept of a windowed GUI, we also owe thanks to thesecreative folks for the Model-View-Controller!

Why Use Design Patterns Anyway?A “Design Pattern” is a collection of objects, and rela-tionships between those objects, that has been devel-oped and tested to efficiently solve a particular class ofproblems. If the problem you are solving matches the

problem solved by a design pattern, then you can geta significant head start on implementing your solutionby adopting the design pattern. You will still need tocustomize the portions of the code for your system, butyou will have a well tested, robust architecture in placeas a base for what you code.

There are many different design patterns to solve avariety of problems. The “bible” of design patterninformation is the book titled “Design Patterns” byErich Gamma, Richard Helm, Ralph Johnson, and JohnVlissides (often called the “Gang of Four”). A goodstarting point for the investigation of PHP design pat-terns is the ::phpPatterns() site(http://www.phppatterns.com/).

Why use MVC?Now that you have been primed with a high-leveloverview of the MVC, and understand that it is a designpattern, you may still wonder why you would want touse it with PHP. The reason is that the MVC pattern is

An IIntroduction tto MMVCUsing PPHP

By Jason E. Sweat

Few design patterns are as 'tried and true' as the ModelView Controller pattern (MVC). In this first part of a twopart series, we'll go over the general philosophy of MVCand why it is useful; what resources are available to helpthe budding MVC coder; and we'll wrap things up with alittle code to drive the concepts home.

PHP Version: 4.0.6+O/S: AnyAdditional Software: Smarty

REQUIREMENTS

Page 2: MVC with PHP

FEATURES

May 2003 · PHP Architect · www.phparch.com 11

An Introduction to MVC Using PHP

a solution for a problem that web sites map to verywell. Each page hit is a user interaction (input) withyour system (the web server processing the PHPscripts). Assuming you have some kind of need tomaintain the state of your data between page hits(using a persistent data store - usually a database orfiles), and you intend to present this information in avariety of ways to the user, then the MVC pattern maybe the architecture you want to use for your applica-tion.

The MVC pattern addresses three problems in archi-tecting a solution:

1. Maintaining your data in some kind of per-sistent storage

2. Maintaining the logic controlling the flow ofthe application, what to display to the user,and what actions the user is allowed to per-form on the data in your application.

3. Presenting information to users of your appli-cation

Each of the three major components of the MVC isclosely associated with one of these goals, as depictedbelow in figure 1.There are a number of resources available on the webto help you start learning about the MVC pattern. Javais a more mature language for enterprise class develop-ment, and PHP developers should feel free to borrowfrom the lessons learned by Java developers. Somegood starting points come from the Sun J2EE specifica-tion; specifically, I recommend reviewing:

Figure 1

• http://java.sun.com/blueprints/patterns/MVC.html

• http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/web-tier/web-tier5.html

• http://developer.java.sun.com/developer/onlineTraining/JSPIntro/contents.html#JSPIntro

4.

Another set of terms you will hear when researchingWeb Based MVC applications is “Model 1” or “Model2”. These are left over from the JSP/J2EE specificationdefinitions of a MVC. The “Model 1” style basicallymeans you have classes to encapsulate the Models inyour system, but the Views are spread out in differentpages, without the flow being guided by theController. The “Model 2” version is the recommend-ed approach, with a Controller object in charge ofapplication flow. It is now recommended that all MVCsystems be implemented as a “Model 2” controller.

There is one more non-PHP project I would like tointroduce to you before taking a closer look at the com-ponents of the Model-View-Controller. The ApacheJakarta Project (http://jakarta.apache.org/) is a high-profile collection of java projects. The MVC for Jakartais called Struts (http://jakarta.apache.org/struts/). Asyou research the subject of Model-View-Controllers, itquickly becomes apparent that Struts is the “GoldStandard” of MVC implementations.

Now that you know what a design pattern is, andwhy MVC is well suited to web applications, let’s havea closer look at the components of a MVC application.

The ModelModels are the portion of the MVC application thatimplement the “Business Logic”. Business logic is anyPHP logic relating to how information is stored in yourapplication.

The name Model comes from that fact that theseobjects emulate things from the real world, both rulesand data. Models are the only component of your sys-tem that should interact with your persistent data store

Note: Implementing this in PHP implies thatyour application will have a single PHP script,using URL or Post parameters to generate thedifferent views in your application. While thisworks well for your coding structure, oldersearch engine applications generally ignoreanything after the “?” in a URL, necessitatingthe use of mod_rewrite, or some other strategy,if making your site search engine friendly is arequirement.

Page 3: MVC with PHP

FEATURES

May 2003 · PHP Architect · www.phparch.com 12

An Introduction to MVC Using PHP

(fancy words for anything that stores and retrieves databetween web requests). Models can implement any ofthe technologies that make PHP such a great languagefor web development: databases calls, file manipula-tion, session management, web services, and anythingelse that stores data for your application.

A well designed model could be used for other appli-cations on your web server. When you start to see thepower of encapsulating your business logic with theseclasses, it becomes clear that making good models is avery useful convention, even if you are not using thefull MVC architecture.

For models that interact with a database table, a sin-gle table should ideally be associated with only onemodel class. This helps you to achieve the first goal welisted for benefits of the MVC: maintaining your data insome kind of persistent data store. By just adhering tothe MVC framework, you only have to review the mod-els in your system if the database table changed. Byadopting this strategy, you would only have a singleclass in the model to review.

Examples of typical models in web applications mightbe the user, the browser, a shopping cart, catalogitems, orders, topics or articles. I find that for database-driven web applications, models tend to be associatedwith a single table, or with a small group of tightly cou-pled tables (perhaps a view?). The name for yourmodel class is likely to be similar to the name for yourdatabase table, assuming you have a reasonable nam-ing convention in place.

I also tend to write model classes for features on thesite. An example of this could be a multi-page form,which may have a “wizard” model associated with it.

The ViewViews are the portion of the MVC application that pres-ent output to the user. The most common output forPHP web applications would be HTML, but views arenot restricted to this. Your MVC application might out-put XML, WML, plain text, images, email or some othercontent. PHP has a variety of capabilities to use inviews, ranging from just being designed to send databack to the browser, to implementing template solu-tions, to XSLT.

Views generally create instances of models, and usemethods of these models to get data to present to theuser. Views contain all of the PHP code required totransform the raw data from your models into the for-mat you want to present in your application. For exam-ple, in the April issue of php|architect, I published anarticle covering the use of PHP for graphing. This kindof graph generation code would belong to views in aMVC.

The ControllerThe controller is the heart of the MVC application. Thiscomponent is the object that should be aware of the

user’s HTTP request (alternatively, the controller mightbe aware of the command line arguments or last inputin a CLI). From this information, the controller shoulddetermine what view to display, or what other applica-tion-related action should take place.

Controllers are generally the core component of anyMVC project you may adopt (primarily because modelsand views must be customized to your application bytheir very nature). Various projects have differentstrategies for determining how the views and modelsinteract. How these objects interact is referred to assystem coupling. If the nature of these relationships isdefined using a configuration file (often XML based),this is said to be “loose coupling”. This is the oppositeof hard coding application flow into your system.

To summarize, figure 1b depicts figure 1 with theappropriate PHP technologies added to each compo-nents sphere of influence.

Will there be any crossover of these technologies inreal world applications? Probably. In fact, one exampleof this is depicted in figure 1b. If your application con-tained a “User” model and you have a “remember me”feature, you might want the User Model to send acookie to the client’s browser. This is technically donevia HTTP, a task which we assigned to the controller. Ihave also had cases where a view might be displayinga particular instance of a model, and which one to dis-play is passed as a parameter of the URL. As a result, theview might access this information using the $_GETsuperglobal (again HTTP bleeding in from the con-troller to the view).

Figure 1b

Where you should not see any crossover of thesetechnologies is between the views and the models. You

Page 4: MVC with PHP

FEATURES

May 2003 · PHP Architect · www.phparch.com 13

An Introduction to MVC Using PHP

should never have any HTML in a model, and youshould never have any database access functions in aview. Having either of these would be a violation ofyour principal of separation of content from format,breaking your MVC model and limiting the flexibility ofyour application.

PHP based MVC ProjectsThere are quite a number of PHP based projects, andother resources to help you evaluate the MVC designpattern (Table 1). Several projects I have located arelisted here. If I have inadvertently omitted an MVCproject you are familiar with, please post a follow up inthe php|architect forum for this article.

Taking Concept to PracticeIn my experience with the MVC pattern for PHP webapplications, there are two general “flow paths”through the MVC application. The first flow path isthat of the user requesting a particular view within the

application. The second typical flow path is that of theuser sending inputs intended to change the state of themodels in the application.

Figure 2 below represents the “request to view” flowpath through the application.

The user’s request (generally an HTTP GET requestfrom a browser) is interpreted by the controller in step1. The controller determines which view is appropriatefor this request. Application flow is turned over to theview in step 2. Generally views will need data to dis-play the the response. This information will come fromthe application Models. Step 3 is the view requestingdata from the model. The model is the only compo-nent in the application that will have PHP code thataccesses a persistent data store. Steps 4 and 5 are themodels request and retrieval of data from the datastore. The model then returns the data in step 6. If theview needs additional data from this or another modelin the application, steps 3 to 6 would be repeated asnecessary. Then the view formats the output and trans-

Project Name / URL Notes

Ambivalencehttp://amb.sourceforge.net/

This project is a port of the java project calledMaverick (http://mav.sourceforge.net/), which origi-nated as an attempt to simplify Struts.

Eocenehttp://eocene.net/

An MVC framework with a goal to port to ASP.NET.

php.MVChttp://www.phpmvc.net/

A port of the java-based Jakarta Struts framework(http://jakarta.apache.org/struts/)

phpPatterns() MVC2http://www.phppatterns.com/index.php/article/articleview/19/1/1/

The second article on this site about the MVC pat-tern.

Phramehttp://phrame.itsd.ttu.edu/

Another port of the Struts framework.

The catchall: google for ithttp://www.google.com/

Searching for "php mvc" yields many results.

Table 1: PHP based projects

Figure 2

Page 5: MVC with PHP

FEATURES

May 2003 · PHP Architect · www.phparch.com 14

An Introduction to MVC Using PHP

mits it to the user as output in the step 7 response.The other common flow path through an MVC web

application is an update to data in the application by auser. This flow path is depicted in figure 3.

The request enters the controller at step 1 (this time,most likely an HTTP POST from the user’s browser).The controller decides what action is appropriate, andcalls a method of the model object with appropriateparameters to reflect the user’s request in step 2. Themodel would determine if the request is valid based onthe business logic you code if the request is valid. If so,the model would alter the data in the store in steps 3and 4. The model would then turn control back to thecontroller in step 5. The controller would determinewhere the user should be directed next, and issue aredirect to that location in step 7. While this is the endof this request (PHP should actually exit after issuing theheader() command), you can think of a conceptualstep 8, which most likely is another request to theapplication to display a particular view.

A Simple MVC ApplicationNow you have enough general background on Model-View-Controllers to walk through a specific example. Inthis example I chose to implement the MVC in theframework from the Phrame project. Phrame is a PHPport of the Jakarta Struts MVC implementation, which Iindicated earlier was the “Gold Standard” of MVCs.Please do not consider me a heretic, but I also liked thefact that Phrame’s configuration was done with a PHParray rather than an XML file.

In Phrame, as in Struts, loose coupling of the modelsand views is accomplished through the addition ofthree more classes, Actions, Forms and Forwards. Eachtime the controller is initiated, it will create an instanceof an Action class you extend from the framework baseAction. The controller will call the Process()method of your Action with a list of Forwards, and aForm object containing all the HTTP request variables.The expected result of your Action is to determine theproper Forward object to return to the controller. Thecontroller will then process the Forward object and exitPHP processing for that request.

This use of the Action object lends itself to an analo-gy between an HTTP request and a sentence. You canthink of Actions as verbs, Models as nouns, and Viewsas adjectives in a sentence. That is, a particular webrequest will perform an Action (verb) on a Model(noun), or display a View which describes (adjective) aModel (noun). The analogy works best for the Actionsand Models, and should be considered when selectingnames for the objects.

This example is a modified version of the “HelloWorld” example from the Phrame project(http://phrame.itsd.ttu.edu/). The source for Phramecan be downloaded from the project’s SourceForgepage, http://sourceforge.net/projects/phrame. The

Note: Some people worry about the over-head caused by the redirect, specifically that itrequires another round trip between the brows-er and the server before the page data is sentback. While this is the case, it is a minor per-formance consideration when compared to thebenefit it enables: the user can hit “refresh”after posting data to your application, and theywill not be prompted by their browser to“repost” the data (because the “last” opera-tion they requested was to GET the redirectedview).

Figure 3

Page 6: MVC with PHP

FEATURES

May 2003 · PHP Architect · www.phparch.com 15

An Introduction to MVC Using PHP

modifications I have made are to eliminate PHP warn-ings (In some cases I modified Phrame library files. Forthese files I renamed them *.jes.php and included theoriginals so you can easily identify the differences),restructuring to better use the advantages of the MVCdesign, and using Smarty templates for View format-ting, rather than XSLT transformation for user output.The MVC application uses a “bootstrap” file, which is asingle PHP script that acts as the focal point for theapplication. In this example, the bootstrap file ishello.php. With that in mind, let’s take a look at thehello.php file, which starts with the application setup:

mvc_code01.php

This code includes library files for Phrame andSmarty. Also included are the actions and models cus-tomized for this application. Two relative URLs aredefined, one for displaying views in the application,and another for HTML Form element action.

In a Phrame application, the relationships betweenthe Forms, Actions and Forwards are established in aPHP array. I found this array tedious to develop andmaintain, and instead created a MappingManager classto maintain these relationships. This class is meant tobe extended for each application developed usingPhrame, and has methods that return arrays in the for-mat Phrame uses. This class has the advantage of vali-dating some of the relationships between the form andaction mappings as you add them (instead of generat-ing an error when you tried to use them in your appli-cation with the regular array configuration). Take alook at the MappingManager.php file included in themagazine download if you are interested in the internalworkings of this class. Presented below is the HelloMapclass, which extends the MappingManager for our

“hello” application.

mvc_code02.php

All of our coding for the HelloMap class is performedin the constructor method. First you have the ability tooverride the typical Phrame options array. In this case,we define a function to use as an error handler whenPhrame is working. Next any forms are identified. Inthis case, there was no need to extend the standardPhrame ActionForm class. Lastly, any actions and for-wards from those actions are defined. In this case, theapplication has a single action (sayHello) with two for-wards, “index” and “hello”. The parameters for theMappingManager::_AddMapping() method are: thename of the mapping, the class that implements themapping, the default location where the action is calledand, lastly, the form mapping associated with thisaction. The MappingManager::_AddForward()method takes parameters for the action mapping iden-tifier it is associated with, an identifier for the forward,and, optionally, a URL to redirect to if not the defaultassociated with the action.

mvc_code03.phpsession_start();

$smarty =& new Smarty;$map =& new HelloMap;$controller =& new

ActionController($map->GetOptions());$errors =& new HelloErrors;

function handle_error($number, $message, $file,$line, $context)

{appl_error($message);

}

function appl_error($psErrorMsg){

$errors =& new HelloErrors;$errors->AddError($psErrorMsg);

}

class HelloMap extends MappingManager{ function HelloMap() {

//set options$this->_SetOptions('handle_error');

//add application forms$this->_AddForm('helloForm',

'ActionForm');

//add application actions and forwards$this->_AddMapping('sayHello',

'HelloAction', APPL_VIEW.'index','helloForm');

$this->_AddForward('sayHello', 'index');$this->_AddForward('sayHello', 'hello',

APPL_VIEW.'hello'); }}

error_reporting(E_ALL);

define('PHRAME_LIB_PATH', '../../phrame/');

require_once PHRAME_LIB_PATH.'include.jes.php';require_once 'Smarty.class.php';require_once 'MappingManager.php';require_once 'actions/HelloAction.php';require_once 'models/Person.php';require_once 'models/HelloErrors.php';

define('APPL_VIEW', 'hello.php?'._VIEW.'=');define('APPL_ACTN', 'hello.php');

"Models can implement any of thetechnologies that make PHP such a

great language for web development"

Page 7: MVC with PHP

FEATURES

May 2003 · PHP Architect · www.phparch.com 16

An Introduction to MVC Using PHP

The next step in this application is to start the session,and create instances of several objects we will be using.These include a Smarty template object, an instance ofthe HelloMap class we just defined, and a PhrameActionController, which needs the options arrayreturned from the MappingManager::GetOptions()method.

This section of code also introduces you to how errorhandling is taking place in this application. There is amodel for errors that encapsulates the actual imple-mentation (which happens to be storing the errors inan array in the $_SESSION, see the HelloErrors.php fileincluded in the download for details). There are alsotwo functions defined. appl_error() allows you toadd an error message to the application error object.handle_error() is a PHP error handler function thatin turn calls the appl_error() function. This meansyou can use appl_error() directly, or use trig-ger_error() whenever the PHP error handling hasbeen set to our handle_error() function.

The rest of the application’s bootstrap file imple-ments the controller component of the MVC.

mvc_code04.php

The ‘if’ statement determines whether or not anaction was requested. If so, then the PhrameActionController::Process() method is called to acti-vate the framework. If an action is not specifically

requested, then a view will be dis-played. The code in the ‘else’statement determines the appro-priate view, assigns view-specificdata to the Smarty template,assigns common data to theSmarty template, processes anyapplication errors, and then ren-ders the template.

With the bootstrap file out ofthe way, we can look at what weadd to the application to enableprocessing with Phrame. The firstthing to consider is what happensin our application if no parame-ters are passed at all. In this case,it will bypass the action process-ing and display the default viewof index.tpl. Here is the essentialportion of the index.tpl Smartytemplate.

mvc_code05.php

It is important to examine what is going on here.There is an HTML form element that is setup to postback to the application script itself. There is a hiddeninput, named by the template variable $action with avalue of “sayHello”. This is the input that directs thecontroller to initiate the “sayHello” mapping.

Note: The input name was specified usingthe template variable $action, which wasassigned the value of the constant _ACTION,which was defined in the Phrame library to bethe index the controller uses to determine if anaction was requested. By default, this value is“action”, but as a good coding habit, we donot hard code the value into our template.

<form action="{$appl_link}" method="post"> <div><input type="hidden" name="{$action}"value="sayHello" /> {if $errors|@count gt 0}

<ul>{section name=e loop=$errors}

<li><b style="color:red">{$errors[e]}</b></li>

{/section}</ul>

{/if}What is your name?<br /> <input type="text" name="name" value="{$name}"/><input type="submit" value="OK" /> </div></form>

if (array_key_exists(_ACTION,$_REQUEST)) {//release control to controller for

//further processing$controller->Process($map->GetMappings(),

$_REQUEST);} else {

//determine and display view$requested_view = (array_key_exists(_VIEW,

$_REQUEST)) ? strtolower($_GET[_VIEW]) :'index';

switch ($requested_view) { case 'hello':

$template = $requested_view.'.tpl';//assign view specific data$person =& new Person;$smarty->Assign('name',

$person->GetName()); break; case 'index': default:

$template = 'index.tpl'; }

//assign common data$smarty->Assign(array(

'appl_link' => APPL_ACTN,'appl_view' => APPL_VIEW,'action' => _ACTION));

//assign and clear errors$smarty->Assign('errors',

$errors->GetErrors());$smarty->Display($template);

exit;}

"Various projectshave differentstrategies for

determining howthe views and

models interact.How these objectsinteract is referredto as 'system cou-

pling'."

Page 8: MVC with PHP

FEATURES

May 2003 · PHP Architect · www.phparch.com 17

An Introduction to MVC Using PHP

The next section of the template is a conditionalcheck for errors. If they are present, they are displayedas an unordered list. The last portion of the template isthe normally visible portion of the form with a textinput for the users name and a submit button.

mvc_ss1.png

So, what happens when the user presses the submitbutton? The browser will submit an HTTP POST operation to the bootstrap script. The $_REQUEST[_ACTION] will contain the value“sayHello”. In response, the $controller will exe-cute the Perform() method. Reviewing the map-pings in our HelloMap class, “sayHello” is associated with the HelloAction class. TheActionController::Perform() method will cre-ate an instance of the HelloAction class and executeHelloAction::Perform(), so that is the next sec-tion of code to review.

mvc_cod06.php

Every action you need to perform in your applicationwill look similar to this file. You will create a class thatextends the Phrame Action class. You need to overridethe Perform() method in your extended class in orderto implement an action. Lastly, your action needs to

return an ActionForward object to the controller tocomplete processing. Let’s examine the details of theHelloAction code.

First of all, for performance reasons I have specifiedboth of the objects passed to the form are by reference,and the function will return the ActionForward objectby reference. Next, two instances of models are creat-ed, $person and $errors. $poActionForm is thePhrame ActionForm class instance created by the con-troller as specified in your mappings. We specified theclass of our form to be ActionForm - the Phrame baseform class itself - because we do not need to extend theform for any reason. The ActionForm class itselfextends the Phrame utility HashMap class, and is “pre-loaded” with the $_REQUEST associative array.Therefore the $poActionForm->Get() method willretrieve a posted variable if it was posted. In this case,we want to evaluate the value of the text input “name”as the value the user submitted.

Next, our action determines which ActionForwardmapping to return by checking if it was successful inexercising the Person::SetName() method of ourmodel. It also verifies no errors were triggered as aresult of this action. If there were problems, it returnsto the “index” view, otherwise, we are clear to showthe “hello” view.

The last step on our tour is to look at the Person.phpfile. Models are unique to applications, and thereforedo not even have a prototype in the Phrame library(they do not have to extend any Phrame classes). Thismodel makes use of two constants, which we attemptto make sure are uniquely named by prefixing themwith the model’s class name.

Reviewing the internal details of our model, we findthe name is stored in the php session. It is importantto note that outside of this class, the details of this stor-age are not known, and you can change this imple-mentation at any time within this class definition. Sinceall access to this session array index in our applicationis performed through this single model class, you caninstitute proper error handling, business logic (like vali-dation rules), and enforcing the consistency of this datafor your application. This all contributes to the MVCgoal of better maintenance of the data in your persist-ent store.

class HelloAction extends Action{ function &Perform(&$poActionMapping, &$poActionForm) {

$person =& new Person();$errors =& new HelloErrors;$name = $poActionForm->Get('name');

//get ActionForward depending on if//errors were generated if ((!$person->SetName($name)) || ($errors->HasErrors())){

$actionForward =$poActionMapping->Get('index');

} else {$actionForward =

$poActionMapping->Get('hello'); } return $actionForward; }

}

"As you research the subject of Mode-View-Controllers, it quickly

becomes apparent that Struts is the'Gold Standard' of MVC

implementations."

Page 9: MVC with PHP

FEATURES

May 2003 · PHP Architect · www.phparch.com 18

An Introduction to MVC Using PHP

Another area of interest in this model is theSetName() method. In particular, our “BusinessLogic” dictates that a name must be less than 20 char-acters. If this method is called with an out of rangevalue, an error will be triggered.

Future Directions:How does one go about expanding this Phrame basedMVC application? If you need an additional view of thedata, you would simply add a new template andextend the case statement for determining valid viewsin the bootstrap file. To add a new action, you wouldneed to create a new class that extends the Action class,similar to the presented HelloAction class. You wouldalso need to add a mapping in the constructor of theHelloMap class so the MVC knows which class toinstantiate when your new action is requested. Finally,you need to add forwards to appropriate views whenthe action completes.

Most of the model classes I have developed for realworld applications deal with databases. This wouldprobably be your next step in developing a more use-ful implementation.

You might also consider how the overall frameworkinteracts. There are two basic facets of the Phrameproject I have altered in most of my implementations.First of all I implemented a “default action” to show aview. Secondly, in this Phrame example, the code pre-sented to display views is not implemented in OO fash-ion. I use the Factory Pattern within the default“ShowView” action to create instances of applicationviews.

Another issue with this example is a small inefficiencyin inclusion of files: the action class is required for everyrequest, even if the result of the particular requestwould be to display a view. You might reconfigure yourapplication to be more aware of this context and onlyinclude appropriate resources.

In Review:We looked at the benefits of implementing PHP scriptsin a MVC framework. We have reviewed an example ofa model using the session for persistent data storage,how the HelloMap and the Phrame ActionControllerallow you to control the flow of the application, andhow Smarty templates can be used to implement viewsin your application.

This example was very simple, but shows processinguser input, data validation, error handling and applica-tion flow. Having reviewed this example, you now pos-sess the fundamental building blocks for deployingyour own MVC based web application.

One benefit people would like to achieve by adopt-ing a coding framework is application developmentspeed. I believe that speed comes with familiarity, anda more immediate benefit is a robust architecture, pro-viding for your deploying a flexible and manageableweb application.

I hope you have found this exposure to the MVC pat-tern useful, and you might consider working with theMVC design pattern for your next interactive webapplication.

About The Author ?>Jason has been an IT professional for over ten years. He is currently anapplication developer and intranet webmaster for a Fortune 100 compa-ny. He has written several tutorials and articles for the Zend website, andhas recently contributed to the Wrox “PHP Graphics” handbook. Heresides in Iowa with his wife and two children. Jason can be contacted [email protected].

Click HERE To Discuss This Articlehttps://www.phparch.com/discuss/viewforum.php?f=19