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. 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.
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/)
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.
Controller.php: Processing Events of Application (User Interaction Of Application)(control page) should never contain SQL queries or HTMLThis 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.
An example of what the code could look like is illustrated below: 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); ? > 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. |