Home >Backend Development >PHP Problem >How to implement route distribution in php
How to implement route distribution in php: 1. Use require and include methods to include php files; 2. Use the path in the url to match the corresponding control class, and call the methods in it to process related operations. .
php method to implement routing distribution:
1. The file contains
There are two ways to include files in php: require and include. The difference between the two methods is that when an error occurs when using require to include the file, a serious error will be reported and the PHP script will stop running; while when an error occurs when using include to include the file , there will be a warning, but the PHP script will still continue to execute. At the same time, both methods include the corresponding xxx_once
method, which can avoid the "declare class" problem. Therefore, when generally using file inclusion, we try to use include_once
to include files.
At the same time, regarding the path issue included in the file, we can use the method of setting global variables to find other path files based on the absolute path of the entry file. Modifying the inclue_path
path in php.ini is of course another way. Use require and include to include the file. If it is a relative path, it will first be based on the include_path# in the php.ini configuration file. ## Settings to look for.
2. Route distribution
PHP-based route distribution is essentially using the path in the URL to match the corresponding control class and calling the methods in it. Processing of related operations. Code without saying a word:<?php // 权限控制 include_once './auth.php'; // 应用入口文件 date_default_timezone_set("Asia/Shanghai"); header('Content-type: text/html;charset=utf-8'); // 项目根路径 define('BASEPATH', dirname(__FILE__)); // 调试模式 define('APP_DEBUG', True); // 引入配置文件 include_once BASEPATH . '/config/config.php'; // 路由控制 $router = include_once BASEPATH . '/config/router.php'; if ($_SERVER['HTTP_HOST'] !== 'xxx.com') { var_dump('当前host不被允许'); } else { $request_path = str_replace('/index.php', '', $_SERVER['PHP_SELF']); $request_query = getCurrentQuery(); if (array_key_exists($request_path, $router)) { $module_file = BASEPATH . $router[$request_path]['file_name']; $class_name = $router[$request_path]['class_name']; $method_name = $router[$request_path]['method_name']; if (file_exists($module_file)) { include $module_file; $obj_module = new $class_name(); if (!method_exists($obj_module, $method_name)) { die("要调用的方法不存在"); } else { if (is_callable(array($obj_module, $method_name))) { $obj_module->$method_name($request_query, $_POST); } } } else { die("定义的模块不存在"); } } else { echo '页面不存在'; } }
Related learning recommendations:php programming (video)
The above is the detailed content of How to implement route distribution in php. For more information, please follow other related articles on the PHP Chinese website!