Table of Contents
您可能感兴趣的文章:
Home Backend Development PHP Tutorial Analysis of basic design ideas and implementation methods of mvc framework implemented by imitating tp in PHP

Analysis of basic design ideas and implementation methods of mvc framework implemented by imitating tp in PHP

Jun 22, 2018 pm 04:24 PM
mvc framework php

这篇文章主要介绍了PHP仿tp实现mvc框架基本设计思路与实现方法,简单讲述了php实现tp框架的原理,并结合实例形式分析了相关控制器、视图及URL访问操作技巧与注意事项,需要的朋友可以参考下

本文实例讲述了PHP仿tp实现mvc框架基本设计思路与实现方法。分享给大家供大家参考,具体如下:

仿tp mvc基本设计与简单实现

一:文件加载常识

变量 常量 函数 类
文件加载的函数或者使用命名空间:require();   require_once();   include();   include_once();
常量:define("DEFINE","");   const constant = "value";
函数:function fun(){}  // global 使用全局变量    局部变量不被外部调用。
类:

<?php
class A{
  public $a = 10;
  public function aa(){  // 不能使用一个a是因为,new A 之后 方法a会被自动执行,所以方法名不可以和类名冲突。
    echo $this->a; // 输出属性.
  }
  public function __construct(){ // 构造方法,实例化后自动执行,
    echo $this->bb(); // 调用方法。
  }
  public function bb(){
    echo "我是bb";
  }
}
$a = new A;
$a->aa();
class B extends A{ // 继承 A ,类A是类B的父级。继承public的,
}
$b = new B;
$b->aa(); // 可以输出类A里面的属性。
Copy after login

工厂模式参阅://www.jb51.net/article/140658.htm

//-----------------------------工厂模式-------------------------//
class A{
  public $class;   // public $class = $_GET[&#39;c&#39;]; //类名
  public $method; // public $method = $_GET[&#39;m&#39;]; //方法
  public function __construct($class,$method){
    // 或者通过 $_SERVER[&#39;PATH_INFO&#39;]; 转换得到类名或者方法名(下面讲解)。
    $this->class = ucfirst(strtolower($class)).&#39;Controller&#39;; //对类名进行安全处理,并加上控制器后缀
    $this->method = strtolower($method);   //对方法名进行安全处理
    $this->work($this->class,$this->method);
  }
  public function work($class,$method){
    // 把文件命名成 (类名.class.php的形式),就可以通过类名找到文件。
    //include &#39;文件名(文件在别的地方)&#39;;    #例如 include &#39;./index.php&#39;; 引入文件然后实例化类。
    $c = new $class;  //实例化类
    $c->$method();  //访问类的方法
  }
}
Copy after login

至此我们可以通过url的 $_GET 参数来解决

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

h为前后台,v为控制器,c为模板。

$v = $_GET[&#39;v&#39;];
$c = rtrim($_GET[&#39;c&#39;],".html");
new A($v,$c); // 根据继承关系再次加载文件。
// extract($arr);  //extract 的作用:从数组中将变量导入到当前的符号表,键做变量,值做值!
// compact(); // — 建立一个数组,包括变量名和它们的值
// assign display 实现参阅://www.jb51.net/article/140661.htm
Copy after login

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 = &#39;&#39;){ // 模板为空自动加载。
    $this->assign($this->key,$this->val);
    extract($this->array);
    // 如果模板为空就在这里根据get参数添加或者通过 $_SERVER[&#39;PATH_INFO&#39;]; 转换得到。(下面讲解)
    if(file_exists($tpl)){ //模板存在就加载文件。
      include $tpl;
    }
  }
}
//继承总model。这个model名字和控制器model的名字是一样的。继承方法同Controller,总model必须需要加上一个return。数据处理的indexmodel可以加return,也可以不加。
class IndexModel extends Model{
  public function index(){
    // 数据处理。
    // 需要返回数据就加上return。
  }
}
class IndexController extends Controller{ // 继承
  public function index(){
    $m = Model("index");
    echo &#39;实例化后的index方法<br>&#39;;
    $this->assign(&#39;m&#39;,$m); // 分配数据。
    $this->display(&#39;index.html&#39;); // 模板
  }
}
Copy after login

mvc虽然实现但是不够人性化,因为每次都要加上get参数,变得很冗长,解决的关键在于$_SERVER[&#39;PATH_INFO&#39;];

用这个替换掉h m v三个参数。

1. 当输入url为:http://mvc.com/index.php/home/index/index.html
这种情况下 index.php 斜线后面的apache会自动认为是一个路径。
$_SERVER[&#39;PATH_INFO&#39;] = /home/index/index.html
第1个斜线 /home 前后台
第2个斜线 /index 控制器
第3个斜线 /index.html 模板文件
如果后面加有参数例如:?a=18&b=38 他不会被加到$_SERVER[&#39;PATH_INFO&#39;]里面。$_POST 或者 $_GET 也不会加入$_SERVER[&#39;PATH_INFO&#39;]里面的内容,这样就可以让控制参数和数据的参数互不冲突。

2. U 方法的实现。重新改写$_SERVER[&#39;PATH_INFO&#39;] 参数,改变为一个数据。array( &#39;home&#39;, &#39;Index&#39;, &#39;index&#39;);

每次进入入口文件index.php都把他的PHP_INFO参数转换为数组,在控制器或者其他的地方只要调用这个参数就行了。

// 这里如果做了大小写的转换,总控制器里面就不用了。
function bca(){
  $arr = explode(&#39;/&#39;,ltrim($_SERVER[&#39;PATH_INFO&#39;],&#39;/&#39;));
  if(count($arr) == 3){
    $arr[0] = strtolower($arr[0]);
    $arr[1] = ucfirst(strtolower($arr[1]));
    // 判断后缀是不是 .html
    if(substr($arr[2],-5,strlen($arr[2])) == &#39;.html&#39;){
      $a = explode(&#39;.&#39;,$arr[&#39;2&#39;]);
      $arr[2] = strtolower($a[0]);
    }else{
      $arr[2] = strtolower($arr[2]);
    }
    $_SERVER[&#39;PATH_INFO&#39;] = $arr;
  }
}
// url方法做控制器或前后台的跳转。第三个参数是输出还是return。默认是直接输出。
function U($string = &#39;&#39;,$method = &#39;&#39;,$bool = true){ // true 是直接输出或者返回,
  // 获取系统变量。
  $path_info = $_SERVER[&#39;PATH_INFO&#39;];
  $script_name = $_SERVER[&#39;SCRIPT_NAME&#39;];
  // 判断中间有没有 / 以确定参数个数。
  if(strpos($string,&#39;/&#39;)){
    $arr = explode(&#39;/&#39;,$string);
    if(count($arr) == 2){  // 两个参数的情况。
      $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){ // 三个参数的情况。
      $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); // 一个参数的情况。
    $url = "/{$path_info[0]}/{$path_info[1]}/{$arr}.html";
  }
  // url 路径的拼接。
  if($method != &#39;&#39;){
    $u = $script_name.$url.&#39;?&#39;.$method;
    if($bool == true){     echo $u;    }else{     return $u;   }
  }else{
    $u = $script_name.$url;
    if($bool == true){     echo $u;    }else{     return $u;   }
  }
}
Copy after login

3. url重写,去掉 index.php

打开apache配置文件重写模块,LoadModule rewrite_module modules/mod_rewrite.so

根下加入的改写文件 .htaccess

内容:

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

在浏览器输入url:http://mvc.com/home/index/index.html?a=19b=38
    [REDIRECT_STATUS] => 200  重写状态ok。

发现 $_SERVER['REDIRECT_URL'];$_SERVER['PATH_INFO']; 参数相同。所以参数后面就可以去掉index.php这安全的问题。

4. 模板替换(思路)

我们会发现有一个我们书写的模板,里面有 {$arr}  等,我们把模板文件读取后通过正则还有字符串把他转换成正常的php文件。对文件名加密后放到替换后的文件夹下,每次url访问的时候查看是否有缓存文件,判断最后修改时间等验证,

5. 数据缓存(思路)

json_encode() json_decode() file_get_contents() file_put_contents(); unserialize();  serialize(); 等存文文件里面或者memcache redis 等存储。

您可能感兴趣的文章:

yii2安装详细流程_php实

PHP实现一维数组与二维数组去重功能示例

CI框架(CodeIgniter)实现的数据库增删改查操作

The above is the detailed content of Analysis of basic design ideas and implementation methods of mvc framework implemented by imitating tp in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles