Analysis of Basic Design Ideas and Implementation Methods of mvc Framework Imitating tp by PHP

  • 2021-10-11 17:57:32
  • OfStack

In this paper, the basic design idea and implementation method of mvc framework based on PHP imitating tp are described. Share it for your reference, as follows:

Basic Design and Simple Implementation of tp mvc

1: File loading knowledge

Variable constant function class
File loading functions or use namespaces: require(); require_once(); include(); include_once();
Constant: define("DEFINE",""); const constant = "value";
Function: function fun(){} //global Use global variables. Local variables are not called externally.
Class:


<?php
class A{
  public $a = 10;
  public function aa(){  //  Can't be used 1 A a Because, new A  After   Method a Will be executed automatically, so the method name cannot conflict with the class name. 
    echo $this->a; //  Output attribute .
  }
  public function __construct(){ //  Construct method, which is automatically executed after instantiation, 
    echo $this->bb(); //  Invoke the method. 
  }
  public function bb(){
    echo " I am bb";
  }
}
$a = new A;
$a->aa();
class B extends A{ //  Inheritance  A , Class A Is a class B The parent of the. Inheritance public Of, 
}
$b = new B;
$b->aa(); //  You can output classes A The attributes inside. 

For factory model, see: https://www.ofstack.com/article/140658. htm


//----------------------------- Factory model -------------------------//
class A{
  public $class;   // public $class = $_GET['c']; // Class name 
  public $method; // public $method = $_GET['m']; // Method 
  public function __construct($class,$method){
    //  Or through  $_SERVER['PATH_INFO'];  Transform to get the class name or method name (explained below). 
    $this->class = ucfirst(strtolower($class)).'Controller'; // Secure the class name and add the controller suffix 
    $this->method = strtolower($method);   // Secure processing of method names 
    $this->work($this->class,$this->method);
  }
  public function work($class,$method){
    //  Name the file   (Class name .class.php You can find the file by the class name. 
    //include ' File name (file is somewhere else) ';    # For example  include './index.php';  Introduces a file and instantiates the class. 
    $c = new $class;  // Instantiate class 
    $c->$method();  // Access the methods of the class 
  }
}

At this point, we can solve it through the $_GET parameter of url

For example: http://mvc.com/index.php? h = home & v=Index & c=index.html

h is the front and back office, v is the controller, and c is the template.


$v = $_GET['v'];
$c = rtrim($_GET['c'],".html");
new A($v,$c); //  Load the file again according to the inheritance relationship. 
// extract($arr);  //extract  The role of: from the array will be imported into the current symbol table, key variables, values do values! 
// compact(); //  -   Establish 1 An array of variables, including variable names and their values 
// assign display  Refer to the implementation: https://www.ofstack.com/article/140661.htm


class Controller{
  public $array;
  public $key;
  public $val;
  public function assign($key,$val){
    if(array($val)){
      $this->array["$key"] = $val;
    }else{
      $this->array["$key"] = compact($val);
    }
  }
  public function display($tpl = ''){ //  Templates are automatically loaded when they are empty. 
    $this->assign($this->key,$this->val);
    extract($this->array);
    //  If the template is empty, it is here according to get Parameter or through the  $_SERVER['PATH_INFO'];  Convert to. (Explained below) 
    if(file_exists($tpl)){ // Load the file when the template exists. 
      include $tpl;
    }
  }
}
// Total inheritance model . This model Name and controller model The name is 1 Like it. Inheritance method is the same as Controller , total model It must be added 1 A return . Data processing indexmodel Can be added return , or not. 
class IndexModel extends Model{
  public function index(){
    //  Data processing. 
    //  If you need to return data, add it return . 
  }
}
class IndexController extends Controller{ //  Inheritance 
  public function index(){
    $m = Model("index");
    echo ' Instantiated index Method <br>';
    $this->assign('m',$m); //  Allocate data. 
    $this->display('index.html'); //  Template 
  }
}

Although mvc is realized, it is not humanized enough, because get parameters are added every time, which becomes very lengthy. The key to solve this problem lies in $_SERVER['PATH_INFO'];

Replace the h m v 3 parameters with this.

1. When the input url is: http://mvc.com/index.php/home/index/index.html
In this case, index. apache after the php slash will automatically be considered as a path.
$_SERVER['PATH_INFO'] = /home/index/index.html
1st slash/home front and back
2nd slash/index controller
Slash 3/index. html template file
If a parameter is added after it, such as:? a=18 & b=38 He will not be added to $_SERVER ['PATH_INFO']. Neither $_ POST nor $_ GET will add the contents of $_ SERVER ['PATH_INFO'], so that the control parameters and data parameters do not conflict with each other.

2. Implementation of U method. Rewrite $_SERVER['PATH_INFO'] Parameter, changed to 1 data. array( 'home', 'Index', 'index');

Each entry file index. php converts its PHP_INFO parameter into an array, which is simply called in the controller or elsewhere.


//  If the case conversion is done here, it will not be used in the master controller. 
function bca(){
  $arr = explode('/',ltrim($_SERVER['PATH_INFO'],'/'));
  if(count($arr) == 3){
    $arr[0] = strtolower($arr[0]);
    $arr[1] = ucfirst(strtolower($arr[1]));
    //  Determine whether the suffix is  .html
    if(substr($arr[2],-5,strlen($arr[2])) == '.html'){
      $a = explode('.',$arr['2']);
      $arr[2] = strtolower($a[0]);
    }else{
      $arr[2] = strtolower($arr[2]);
    }
    $_SERVER['PATH_INFO'] = $arr;
  }
}
// url Method to do the jump of controller or front and back office. No. 1 3 Is the parameter output or return . The default is direct output. 
function U($string = '',$method = '',$bool = true){ // true  Is directly output or returned, 
  //  Gets the system variable. 
  $path_info = $_SERVER['PATH_INFO'];
  $script_name = $_SERVER['SCRIPT_NAME'];
  //  Judge whether there is any in the middle  /  To determine the number of parameters. 
  if(strpos($string,'/')){
    $arr = explode('/',$string);
    if(count($arr) == 2){  //  The case of two parameters. 
      $arr[0] = ucfirst(strtolower($arr[0]));
      $arr[1] = strtolower($arr[1]);
      $url = "/{$path_info[0]}/{$arr[0]}/{$arr[1]}.html";
    }else if(count($arr) == 3){ // 3 Parameters. 
      $arr[0] = strtolower($arr[0]);
      $arr[1] = ucfirst(strtolower($arr[1]));
      $arr[2] = strtolower($arr[2]);
      $url = "/{$arr[0]}/{$arr[1]}/{$arr[2]}.html";
    }
  }else{
    $arr = strtolower($string); // 1 Parameters. 
    $url = "/{$path_info[0]}/{$path_info[1]}/{$arr}.html";
  }
  // url  Splicing of paths. 
  if($method != ''){
    $u = $script_name.$url.'?'.$method;
    if($bool == true){     echo $u;    }else{     return $u;   }
  }else{
    $u = $script_name.$url;
    if($bool == true){     echo $u;    }else{     return $u;   }
  }
}

3. Rewrite url, remove index. php

Open the apache configuration file rewrite module, LoadModule rewrite_module modules/mod_rewrite. so

Overwrite file added under root. htaccess

Content:


<IfModule mod_rewrite.c>
 Options +FollowSymlinks
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>

Enter url in the browser: http://mvc.com/home/index/index.html? a=19b=38
[REDIRECT_STATUS] = > 200 override state ok.

Discover require_once();0 And $_SERVER['PATH_INFO']; Parameters are the same. Therefore, the security problem of index. php can be removed after the parameter.

4. Template replacement (idea)

We will find that there is a template we wrote with {$arr} in it < include file="" / > After reading the template file, we convert it into a normal php file through regularization and string. Encrypt the file name and put it in the folder after replacement. Check whether there is a cache file every time url accesses, judge the last modification time and other verification.

5. Data caching (ideas)

json_encode() json_decode() file_get_contents() file_put_contents(); unserialize(); serialize(); memcache redis and so on.

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this paper is helpful to everyone's PHP programming.


Related articles: