search
HomeBackend DevelopmentPHP TutorialAnalysis of basic design ideas and implementation methods of mvc framework implemented by imitating tp in 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里面的属性。

工厂模式参阅://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();  //访问类的方法
  }
}

至此我们可以通过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

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;); // 模板
  }
}

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

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

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

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

每次进入入口文件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;   }
  }
}

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>

在浏览器输入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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.