Analysis of Class Implementation Method for PHP to Build its own MVC Framework from scratch

Time:2019-9-8

This paper illustrates the way PHP builds its own MVC framework from scratch through class implementation. Share for your reference, as follows:

staycoreUnder the directory, create a new name calledlibSubdirectories, and then write us in front of themroute.phpThis file is moved to this directory.

Because the path of the route class file is modified, when instantiating:


new \core\lib\route();

Then we can perfect it.route.php:

<?php
namespace core\lib;
class Route
{
  Public $controller; //controller
  Public $action; // method (action)
  public function __construct()
  {
    // xxx.com/index.php/index/index
    // xxx.com/index.php/index
    /*
     * 1. Hide index. PHP
     * 2. Get the URL parameter section
     * 3. Return to the corresponding controller and method
     * */
    if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/'){
      // Processing into this format: index / index
      $path = $_SERVER['REQUEST_URI'];
      $pathArr = explode('/',trim($path,'/'));
      if(isset($pathArr[0])){
        $this->controller = $pathArr[0];
      }
      unset($pathArr[0]);
      if(isset($pathArr[1])){
        $this->action = $pathArr[1];
        unset($pathArr[1]);
      }else{
        $this->action = 'index';
      }
      // Converting the redundant part of URL (parameter part) to GET
      // id/1/str/2
      $count = count($pathArr) + 2;
      $i = 2;
      while($i < $count){
        if(isset($pathArr[$i + 1])){
          $_GET[$pathArr[$i]] == $pathArr[$i + 1];
        }
        $i = $i + 2;
      }
      P($_GET); //Print GET
    }else{
      $this - > controller = index;// default controller
      $this - > action ='index'; // default method
    }
  }
}

More readers interested in PHP-related content can see the topics of this site: Introduction to Php Object-Oriented Programming, Introduction to PHP Array Operating Skills, Introduction to PHP Basic Grammar, Summary of PHP Operating and Operator Usage, Summary of Php String Usage, and php+mysql Data. Introduction to Library Operations and Summary of Common Database Operating Skills in PHP

I hope this article will be helpful to everyone’s PHP program design.