PHP to develop a simple MVC

Source: Internet
Author: User

This article introduces the method of developing a simple MVC with PHP, which plays the role of the potential brick to lead the jade, this article is more suitable for the friend who just contact MVC. MVC is actually the abbreviation for three model,contraller,view words. Model, the primary task is to read the data in the database or other file system as we need it. View, mainly responsible for the page, the data in the form of HTML display to the user. Controller, mainly responsible for business logic, according to the user request for the allocation of requests, such as display login interface, you need to call a controller Usercontroller method loginaction to display.

This article shows you how to use PHP to create a simple MVC architecture system.

Start by creating a single point of entry, the bootstrap file index.php, as the only entry for the entire MVC system. What is a single point of entry? The so-called single-point entry is the entire application with only one entry, and all implementations are forwarded through this portal. Why do we have to do a single point of entry? There are several advantages to a single point entry: First, some system-wide variables, classes, and methods can be handled here. For example, you want to filter the data initially, you want to simulate session processing, you need to define some global variables, even if you want to register some objects or variables into the registrar. Second, the structure of the procedure is more clear and concise.

    1. Include ("core/ini.php");
    2. Initializer::initialize ();
    3. $router = loader::load ("router");
    4. Dispatcher::d Ispatch ($router);
Copy Code

This document only has 4 sentences, we now have a sentence to analyze. include ("core/ini.php");

Let's see 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. }
Copy Code

This file first sets up the include_path, that is, if we want to find the included files, tell the system to look in this directory. In fact, we define the __autoload () method, this method is added in the PHP5, that is, when we instantiate a function, if this file does not, it will automatically load the file. The official explanation is: Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is has to write a long list of needed includes at the beginning of each script (one for E Ach class).

In PHP 5, this is no longer necessary. You could define an __autoload function which was automatically called in case you were trying to use a class/interface which Hasn ' t been defined yet. By calling this function, the scripting engine is given a, chance to load, the class before PHP fails with an error.

Next we look at the following sentence initializer::initialize (); This is called a static function of the initializer class initialize, because we set the include_path in ini.php, and defined __autoload, so the program will automatically core/ The main directory looks for the initializer.php.initializer.php file 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/config.php");
    12. }
    13. }
    14. ?>
Copy Code

This function is very simple, just define a static function, initialize function, this function is set include_path, so that later if the inclusion of files, or __autoload, will go to these directories to find.

OK, let's go on, look at the third sentence $router = loader::load ("router");

This sentence is also very simple, is loaded loader function static function load, below we come to 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. }
Copy Code

This file is to load the object, because later we may enrich this MVC system, there will be model,helper,config and so on components. If the loaded component is not in a valid range, we throw an exception. If so, we instantiate an object, which in fact uses a single-piece design pattern. That is, this object can only be an instantiated object, if not instantiated, create a, if present, do not instantiate.

OK, because we're going to load the router component now, so let's look at the router.php file, the function of which 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. }
Copy Code

We can see that first we get the URL of $_get, the user request, and then we parse out the controller and action from the URL, and the params like our address is http://www.tinoweb.cn/user/ PROFILE/ID/3 so from the above address, we can get the controller is user,action seems to profile, parameter is ID and 3

Ok we look at the last sentence, that is dispatcher::d ispatch ($router);

The meaning of this sentence is very clear, is to get the results of the URL parsing, and then through the dispatcher to distribute controlloer and action to response to the user good, we look at the dispatcher.php file

    1. !--? class dispatcher

    2. {
    3. public static function Dispa TCH ($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. }

Copy Code

This class is obviously to get $router to find the Controller and action in the file in response to the user's request. OK, we have a simple, MVC structure, so, of course, this is not a very complete MVC, because there is no view and model involved, I am rich here. Let's write a controller file to test the system above. We 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. }
Copy Code

You can then enter Http://localhost/index.php?user/register or Http://localhost/index.php?user/login in the browser to test it.

  • Related Article

    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.