


PHP imitates tp to implement the basic design ideas and implementation methods of the mvc framework
这篇文章主要介绍了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里面的属性。
工厂模式参阅:http://www.jb51.net/article/140658.htm
//-----------------------------工厂模式-------------------------// class A{ public $class; // public $class = $_GET['c']; //类名 public $method; // public $method = $_GET['m']; //方法 public function __construct($class,$method){ // 或者通过 $_SERVER['PATH_INFO']; 转换得到类名或者方法名(下面讲解)。 $this->class = ucfirst(strtolower($class)).'Controller'; //对类名进行安全处理,并加上控制器后缀 $this->method = strtolower($method); //对方法名进行安全处理 $this->work($this->class,$this->method); } public function work($class,$method){ // 把文件命名成 (类名.class.php的形式),就可以通过类名找到文件。 //include '文件名(文件在别的地方)'; #例如 include './index.php'; 引入文件然后实例化类。 $c = new $class; //实例化类 $c->$method(); //访问类的方法 } }
至此我们可以通过url的 $_GET 参数来解决
例如:http://mvc.com/index.php?h=home&v=Index&c=index.html
h为前后台,v为控制器,c为模板。
$v = $_GET['v']; $c = rtrim($_GET['c'],".html"); new A($v,$c); // 根据继承关系再次加载文件。 // extract($arr); //extract 的作用:从数组中将变量导入到当前的符号表,键做变量,值做值! // compact(); // — 建立一个数组,包括变量名和它们的值 // assign display 实现参阅:http://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 = ''){ // 模板为空自动加载。 $this->assign($this->key,$this->val); extract($this->array); // 如果模板为空就在这里根据get参数添加或者通过 $_SERVER['PATH_INFO']; 转换得到。(下面讲解) 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 '实例化后的index方法<br>'; $this->assign('m',$m); // 分配数据。 $this->display('index.html'); // 模板 } }
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('/',ltrim($_SERVER['PATH_INFO'],'/')); if(count($arr) == 3){ $arr[0] = strtolower($arr[0]); $arr[1] = ucfirst(strtolower($arr[1])); // 判断后缀是不是 .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方法做控制器或前后台的跳转。第三个参数是输出还是return。默认是直接输出。 function U($string = '',$method = '',$bool = true){ // true 是直接输出或者返回, // 获取系统变量。 $path_info = $_SERVER['PATH_INFO']; $script_name = $_SERVER['SCRIPT_NAME']; // 判断中间有没有 / 以确定参数个数。 if(strpos($string,'/')){ $arr = explode('/',$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 != ''){ $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. 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}
5. 数据缓存(思路)
json_encode()
json_decode()
file_get_contents()
file_put_contents();
unserialize();
serialize();
等存文文件里面或者memcache redis 等存储。
相关推荐:
The above is the detailed content of PHP imitates tp to implement the basic design ideas and implementation methods of the mvc framework. For more information, please follow other related articles on the PHP Chinese website!

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

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),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

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.