Home >Backend Development >PHP Problem >What are the single entrances to the PHP framework?
In a single file entry application, all requests are received through index.php and forwarded to the function code, so some things become much simpler, such as data security checks, access statistics, etc.
Some of the more popular PHP development frameworks such as Laravel, ThinkPHP, etc. all adopt the single entry mode.
Let’s implement a simple version of a single file entry framework, including the implementation of MVC architecture and URL routing.
MVC architecture (Recommended learning: PHP programming from entry to proficiency)
Controller controller is the interaction between Model and View As an intermediary, the Model layer is responsible for reading and writing data, and the View layer is responsible for view processing output.
URL routing principle
The basic idea is that the browser provides the name of the controller class and the name of the method through the URL string, and PHP finds the corresponding class and method accordingly. method.
To facilitate testing, all functions are written in one file. In the actual framework, each class is a file and the entry is a file.
<?php/** * PHP单一文件框架设计简析 * 1、MVC架构实现 * 2、URL路由原理 *///URL路由原理/** * 路由作用 * 获取url中的c和a变量,执行c类对应的方法a,实现不同的路由 */class App { public $c; public $a; public function run() { $c = isset($_GET['c']) ? $_GET['c'] : "Index"; //url提供类名字的变量名 $a = isset($_GET['a']) ? $_GET['a'] : "Index"; //url提供方法名字的变量名 $c .= "Controller"; if( class_exists($c) && method_exists($c, $a) ) { $o = new $c(); $o->$a(); }else{ echo "error"; exit(); } }}//MVC架构/** * 模型层 * 获取应用数据作用 */class Model { //TODO:link db、get data}/** * 视图类 * 编译、缓存及显示模板 */class View { public function render($tpl) { echo "Hi, ".$tpl; //TODO:具体html模板 }}/** * 控制器 * 所有功能控制器继承该类 */class Controller { public $view; public $model; public function __construct() { $this->view = new View(); $this->model = new Model(); } public function display($tpl = "") { echo $this->view->render($tpl); exit(); }}//具体功能开发class IndexController extends Controller { /** * 网站首页 */ public function Index() { $this->display("Index"); } /** * 网站列表 */ public function List() { $this->display("List"); }}//单一文件入口$app = new App();$app->run();?>
Save the above code as index.php, and then browse
http://localhost/index.php?c=Index&a=Index
http://localhost/ index.php?c=Index&a=List
You can see that different content is output after our routing!
The above is the detailed content of What are the single entrances to the PHP framework?. For more information, please follow other related articles on the PHP Chinese website!