Introduction to MVC in PHP (2)

xiaoxiao2021-03-06  14

(Walter.fan compiled from Jason E. SWEAT Write PHP) Next to see a simple MVC application instance: said that the sky is a lotus, it is better to act and make a simple example. In this example, we Implement the MVC mode with a Phrame frame. Phrame is a PHP implementation of Jakarta Struts, which is an XML file as Struts, but the most common array in PHP.

In Phrame, like Struts, the models and views are loosely coupled together through the Action, Forms and Forwards. Every Controller initializes, it creates an instance of the subclass of the Action class, CONTROLLER will call you. Action subclass's process () method, a list of Forwards and a FORM object containing all HTTP Request variables

Your Action's expectations are to determine that the appropriate Forward object returns to controller.controller handles this Forward object and exits the processing process for this request.

The action of an action object, can do a class between HTTP Request and a sentence than you can think that in this sentence, action is a verb, Model is a noun, and the view is an adjective. In other words, a specific The web request will execute an action on a model (noun), or display a view to describe a Model (noun)

This type describes the Action and Model relationships, and can consider when selecting an object name.

This example is a modified version of Phrame's Hello World example (http://phrame.itsd.ttu.edu/). Source code can be downloaded from http://sourceforge.net/projects/phrame in this example, I have dropped Some warnings of PHP, use Smarty instead of XSLT to format the view

The MVC application uses a bootstap file, which is a separate PHP file. This bootstap file is Hello.php, let's take a look at this bootstap file In a phrame program, the relationship between Forms and Forwards is built in the traditional phrame option array. I think this array monotonous length is not conducive to development and maintenance creation a mappingmanager class. Management Maintenance These relationships This class can be extended by any Phrame application, which has a way to return PhP arrays used by Phrame. The advantage of this class is to enhance their access to the relationship between Form and Action Mapping (avoiding You try to generate an error when using the phrame option array) 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 (' Sayello ' , 'index'); $ this -> _ addforward ('SayHello', 'Hello');}} During the Hellomap Class constructor, we have to do it. First, overload the traditional phrame An array of options, we define an error handling function Next, see what form needs to identify, in this example, there is no need to extend the standard Phrame Actionform class Finally, define Actions and Forwards, this example, only one action: SayHello two Forwards : "INDEX" and "Hello" mappingmanager :: _ addmapping () method are parameters (mapping name, implementing this mapping class, calling Action default address, mapping with action with action)

The parameters of the mappingmanager :: _ addforward () method are the identifiers of the action maping, the IRL of the Forward identifier, and an optional redirect URL (if there is no Action associated with it)

getOptions ()); $ error = & new helloerrors; function handle_ERROR ($ Number, $ Number, $ Number, $ Number, $ Number, $ Number, Message, $ FILE, $ LINE, $ Context) {appl_error ($ message);} Function Appl_ERROR ($ PSERRMSG) {$ Errors = & new helloerror; $ error-> adderror ($ pSERRORMSG);}?>

Next, we start the session, create a few objects we want to use Smarty Template ObjectHellomap Class Object (which is previously defined) Phrame ActionController Object (it requires an option array, can be obtained by mappingmanager :: getOptions ()

The code in this section also joined an error Model, encapsulated an error handling actual implementation (saving errors in one data of $ _SESSION, see HelloerRors.php)

And define two functions appl_error (), allowing you to add an error to the system's error object to the Handle_Error () a PHP error handler, which calls the function appl_error () that you can directly use the function Appl_ERROR (). Or use Trigger_ERROR () (if the PHP error handler handle is set to Handle_ERROR ())

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-> getRrors ()); $ smarty-> display; exit;} The remaining code implements the MVC's Controller component if statement determines whether to request an action. If yes, call phrameActionController :: Process Method activates this framework. If there is no specified request, display a ViewElse statement to determine the appropriate view, Assign specific data to the Smarty template Assign General data to the smarty template to process any possible error and then render Template

Jump out of this program, let's see what we are adding in our application to use phrame first, think about what if there is no parameters to pass in, our application should do. In this example, skip Action Processing, render Index .tpl template to display the default view here is part of Smarty Template Index.tpl

{if $ errors | @count GT 0 }
    {section name = e loop = $ error}
  • {$ Errors [e]} {/ section} {/ if} What is your name?
    < / div> is to check what is going on. This HTML form is submitted to the application script itself. It has a hidden variable, named "Sayello" with template variable $ action, which is to guide Controller to initialize "SayHello" mapping input.

    The following section of the template is an error condition check. If there is an error, it will display a unordered list. The last part of the template is the display section of the usual form, a user name text input box and a submission button

    So, what will the user clicks the submission button? The browser will submit an HTTP POST to this bootstrap script. $ _ Request [_action] value is "Sayello". As a response, $ controller will perform a perform () method to review our Mapping, "Sayhello" and HelloAction class in the HelloMap class, and the HelloActionController :: Perform () method creates an instance of the HelloAction class and executes the HelloAction :: Perform () method, see the code below

    Class HelloAction Extends Action {Function & Perform (& $ PoActionMApping, & $ POACTIONFORM) {$ Person = & new person (); $ error = & new helloerror; $ name = $ PoActionform-> Get ('name'); // Get ActionForward Depending on if // Errors Were Generated IF ($ Person-> SetName) || ($ ERRORS-> HaserRors ()) {$ actionforward = $ pipemapping-> get ('index'); } Else {$ actionforward = $ pipesmapping-> get ('Hello');} returnidforward;}}

    Every action you need in your application is similar to this file. You can create a subclass of Phrame Action, and reload the Perform () method to implement an action, your program needs to return an actionforward object to Controller Go to complete the processing.

    Let's take a look at the details of the HelloAction code. Because of performance reasons, the function of passing two specified objects to the function Perform This will return an actionforward object in an address mode and then create a model $ Person and $ Person and $ Person and $ Person ERRORS. $ PoActionForm is the instance of the Phrame Actionform class created by your mappings based on your mappings, instead of inheriting it, because there is no necessary reason the Actionform class inherits Phrame tool class HashMap class, and $ _REQUEST related data preload, if the POST is submitted, the $ pactionform-> get () method will get the Posted variable in this case, we want to ask the Name entered in the text input box submitted by the user, according to Medel The Person :: setName () method is successful, which is determined by our Action. Which ActionForward Mapping is returned. It also verifies that this ActionR result is not error trigger. If there is a problem, it will return to "index" view, otherwise, obviously display "Hello" View. Let's take a look at the Person.php file. For each application, Models is unique, so it is impossible to have prototypes in the phrame library, nor does it have to inherit any class from the Phrame class. This Model uses two constants to use them as the prefix of the Model class name to avoid the rename.

    Review the internal details of our model, we found that the name is saved in the session of PHP. Focus on it in our class, this storage detail is unknown, you can change the definition of the class at any time to change this implementation method. Since all the operations of the SESSION data index in our application are complete by the SLDEL class, you can create the correct error handling, business logic (similar to confirmation rules) and strengthen your application data. Consistency. This is the contribution of MVC, so that we may better maintain data in persistent storage.

    Another interested in this model is the setName () method, especially, our business logic specifies that a name must be less than 20 characters. If this model is called with an outward name length value, it will trigger one error

    How does the future How to expand Phrame-based MVC applications? If you need an additional data view, you can simply add a new template and extend the "CASE" statement to determine an effective view in the bootstrap file.

    To add a new action, you need to create a new class that inherits the Action is like the HelloAction class we wrote, you also need to add mapping in the Hellomap class's constructor so that MVC knows when requesting new Action. Which class is initialized, when the Action is completed, you need to add Forwards to point to the right view.

    Most Model classes we develop will use the database. Many times, we have two basic changes for phrame. First, implement a default action to display a view, in this case, it is not fully implemented Object-style, one instance of the application view can be created in the Factory mode in the default "showView" action

    Another problem with this example is that the included file is a bit inefficient: each request needs to include the Action class, even display a special request for the result of the result of a special request. You can reset your application, more sensitive to the context, only necessary Resource.

    Looking back, we have seen the benefits of implementing PHP with the MVC framework. I look at the model used as a persistent data storage, how to use Hellomap and Phrame and ActionController to control the process of the application, how to use Smarty in the application Templates to implement View

    This example is very simple, but it demonstrates the process of handling user input, data check, error handling, and application procedures. We have the basis for developing MVC-based web programs.

转载请注明原文地址:https://www.9cbs.com/read-50868.html

New Post(0)