Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Download
Standard view
Full view
of .
Look up keyword
Like this
138Activity
0 of .
Results for:
No results containing your search query
P. 1
MVC with PHP

MVC with PHP

Ratings:

4.83

(6)
|Views: 12,784 |Likes:
Published by jewelbd

More info:

Published by: jewelbd on Aug 24, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

01/30/2013

pdf

text

original

 
FEATURES
FEATURES
May 2003
· PHP Architect· www.phparch.com
10
An
I
ntroduction
t
o
M
VCUsing
P
HP
 
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 for a 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 data from 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 of problems. If the problem you are solving matches theproblem 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, but you 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 John Vlissides (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
I
ntroduction
t
o
M
VCUsing
P
HP
 
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 twopart series, we'll go over the general philosophy of MVC and why it is useful; what resources are available to helpthe 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
 
FEATURES
May2003
· 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) with your 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 or  files), 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 storage2. Maintaining the logic controlling the flow of the 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-cationEach 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 borrow from 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.htmlhttp://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/web-tier/web-tier5.htmlhttp://developer.java.sun.com/developer/onlineTraining/JSPIntro/contents.html#JSPIntro4.
 Another set of terms you will hear when researching Web 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 in your 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 of application 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/
 
). As you 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 Model
Models are the portion of the MVC application thatimplement the “Business Logic”. Business logic is anyPHP logic relating to how information is stored in your application.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 that your application will have a single PHP script,using URL or Post parameters to generate the different views in your application. While this works well for your coding structure, older search engine applications generally ignore anything after the “?” in a URL, necessitating the use of mod_rewrite  , or some other strategy,if making your site search engine friendly is a requirement.
 
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 of the technologies that make PHP such a great language for 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 the full 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 your model class is likely to be similar to the name for your database 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 View
 Views are the portion of the MVC application that pres-ent output to the user. The most common output for PHP 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 other content. 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 Controller
The controller is the heart of the MVC application. Thiscomponent is the object that should be aware of theuser’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

Activity (138)

You've already reviewed this. Edit your review.
1 hundred reads
1 thousand reads
David Duong added this note
ffgfgf
Luke Chamba added this note
why is this document not free printable or downloadable ...?
Ahmad Aqueel liked this
Rai Sugiarta liked this
Rai Sugiarta liked this
glotonprueba2 liked this
Eman Lopez liked this

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->