Php development a simple MVC-php Tutorial

Source: Internet
Author: User
Php develops a simple MVC

This article describes how to use php to develop a simple mvc method through examples. This article is suitable for those who are new to mvc. MVC is actually the abbreviation of three models, Contraller and View words. Model, the main task is to read the data of the database or other file systems as needed. View, mainly responsible for page display data to users in html format. The Controller is mainly responsible for business logic. it allocates requests based on user requests. for example, if the login interface is displayed, you need to call the loginAction method of the Controller userController to display the Request.

This article describes how to use PHP to create a simple MVC structure system.

Create a single point of entry, that is, index. php of the bootstrap file, as the only entry to the entire MVC system. What is a single point of access? The so-called single point of entry means that the entire application has only one entry, and all implementations are forwarded through this entry. Why is single point of access required? The single point entry has several benefits: first, some variables, classes, and methods processed globally by the system can be processed here. For example, if you want to preliminarily filter data and simulate session processing, you need to define some global variables, or even register some objects or variables into the register. Second, the program architecture is clearer and clearer.

  1. Include ("core/ini. php ");
  2. Initializer: initialize ();
  3. $ Router = loader: load ("router ");
  4. Dispatcher: dispatch ($ router );

There are only four sentences in this file. we will analyze the sentence now. Include ("core/ini. php ");

Let's take a look at core/ini. php.

  1. Set_include_path (get_include_path (). PATH_SEPARATOR. "core/main ");
  2. // Set_include_path-Sets the include_path configuration option
  3. Function _ autoload ($ object ){
  4. Require_once ("{$ object}. php ");
  5. }

This file first sets include_path, that is, if we want to find the contained file, tell the system to find it in this directory. In fact, we define the _ autoload () method. this method is added in PHP5, that is, when we instantiate a function, if this file does not exist, it will automatically load the file. Official explanation: includevelopers writing object-oriented applications create one PHP source file per-class definition. one of the biggest annoyances is having to write a long list of needed classes des at the beginning of each script (one for each class ).

In PHP 5, this is no longer necessary. you may define an _ autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. by calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Next, let's take a look at the following sentence initializer: initialize (); this is to call a static function initialize of The initializer class, because in ini. php, set include_path and define _ autoload, so the program will automatically find initializer in the core/main directory. php. initializer. the PHP file is as follows:

  1. Class initializer
  2. {
  3. Public static function initialize (){
  4. Set_include_path (get_include_path (). PATH_SEPARATOR. "core/main ");
  5. Set_include_path (get_include_path (). PATH_SEPARATOR. "core/main/cache ");
  6. Set_include_path (get_include_path (). PATH_SEPARATOR. "core/helpers ");
  7. Set_include_path (get_include_path (). PATH_SEPARATOR. "core/libraries ");
  8. Set_include_path (get_include_path (). PATH_SEPARATOR. "app/controllers ");
  9. Set_include_path (get_include_path (). PATH_SEPARATOR. "app/models ");
  10. Set_include_path (get_include_path (). PATH_SEPARATOR. "app/views ");
  11. // Include_once ("core/config. php ");
  12. }
  13. }
  14. ?>

This function is very simple. it only defines a static function, initialize function. This function is used to set include_path. in this way, if a file or _ autoload is included in the future, it will be searched under these directories.

OK. Let's continue. see the third sentence $ router = loader: load ("router ");

This sentence is also very simple, that is, loading the static function load of the loader function. next we will use loader. php

  1. Class loader
  2. {
  3. Private static $ loaded = array ();
  4. Public static function load ($ object ){
  5. $ Valid = array ("library ",
  6. "View ",
  7. "Model ",
  8. "Helper ",
  9. "Router ",
  10. "Config ",
  11. "Hook ",
  12. "Cache ",
  13. "Db ");
  14. If (! In_array ($ object, $ valid )){
  15. Throw new Exception ("Not a valid object '{$ object}' to load ");
  16. }
  17. If (empty (self: $ loaded [$ object]) {
  18. Self: $ loaded [$ object] = new $ object ();
  19. }
  20. Return self: $ loaded [$ object];
  21. }
  22. }

This file is used to load objects, because in the future we may enrich this MVC system, and there will be components such as model, helper, and config. If the loaded component is not within the valid range, an exception is thrown. If so, we instantiate an object. In fact, the single-piece design mode is used here. That is, this object can only be an instantiated object. if it is not instantiated, create one. if it exists, it is not instantiated.

Okay, because we want to load the router component now, let's take a look at the router. php file. The role of this file is to map the URL and parse the URL. Router. php

  1. Class router
  2. {
  3. Private $ route;
  4. Private $ controller;
  5. Private $ action;
  6. Private $ params;
  7. Public function _ construct ()
  8. {
  9. $ Path = array_keys ($ _ GET );
  10. If (! Isset ($ path [0]) {
  11. If (! Empty ($ default_controller ))
  12. $ Path [0] = $ default_controller;
  13. Else
  14. $ Path [0] = "index ";
  15. }
  16. $ Route = $ path [0];
  17. $ This-> route = $ route;
  18. $ RouteParts = split ("/", $ route );
  19. $ This-> controller = $ routeParts [0];
  20. $ This-> action = isset ($ routeParts [1])? $ RouteParts [1]: "base ";
  21. Array_shift ($ routeParts );
  22. Array_shift ($ routeParts );
  23. $ This-> params = $ routeParts;
  24. }
  25. Public function getAction (){
  26. If (empty ($ this-> action) $ this-> action = "main ";
  27. Return $ this-> action;
  28. }
  29. Public function getController (){
  30. Return $ this-> controller;
  31. }
  32. Public function getParams (){
  33. Return $ this-> params;
  34. }
  35. }

We can see that first we GET $ _ GET, the URL of the user Request, then we parse the Controller and Action from the URL, and Params. for example, our address is callback.

OK. Let's take a look at the last sentence: dispatcher: dispatch ($ router );

The meaning of this sentence is very clear, that is, get the URL resolution result, and then use dispatcher to distribute controlloer and action to Response to the user. let's take a look at the dispatcher. php file.

  1. Class dispatcher

  2. {
  3. Public static function dispatch ($ router)
  4. {
  5. Global $ app;
  6. Ob_start ();
  7. $ Start = microtime (true );
  8. $ Controller = $ router-> getController ();
  9. $ Action = $ router-> getAction ();
  10. $ Params = $ router-> getParams ();
  11. $ Controllerfile = "app/controllers/{$ controller}. php ";
  12. If (file_exists ($ controllerfile )){
  13. Require_once ($ controllerfile );
  14. $ App = new $ controller ();
  15. $ App-> setParams ($ params );
  16. $ App-> $ action ();
  17. If (isset ($ start) echo"

  18. Tota1l time for dispatching is: ". (microtime (true)-$ start)." seconds .";

  19. $ Output = ob_get_clean ();
  20. Echo $ output;
  21. } Else {
  22. Throw new Exception ("Controller not found ");
  23. }
  24. }
  25. }

This class is obvious, that is, get $ router to find the controller and action in the file to respond to the user's request. OK, we have a simple MVC structure. of course, it cannot be regarded as a complete MVC, because View and Model are not involved yet. I will enrich them here when I have time. Let's write a Controller file to test the above system. Create a user. php file under app/controllers/// user. php

  1. Class user
  2. {
  3. Function base ()
  4. {
  5. }
  6. Public function login ()
  7. {
  8. Echo 'login html page ';
  9. }
  10. Public function register ()
  11. {
  12. Echo 'register html page ';
  13. }
  14. Public function setParams ($ params ){
  15. Var_dump ($ params );
  16. }
  17. }

Then, you can enter http: // localhost/index. php in the browser? User/register or http: // localhost/index. php? User/login to test.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.