[PHP] url的pathinfo模式加载不同控制器的实现
2023-02-18 15:47:24 时间
使用自动加载和解析url的参数,实现调用到不同的控制器,实现了pathinfo模式和普通的url模式
文件结构:
|--Controller
|--Index
|--Index.php
|--Application.php
Application.php
<?php class Application{ public static function main(){ header("content-type:text/html;charset=utf-8"); self::register(); self::router(); } public static function register(){ spl_autoload_register("self::loadClass"); } public static function loadClass($class){ $class=str_replace('\\', '/', $class); $class="./".$class.".php"; require_once $class; } public static function router(){ if(isset($_SERVER['PATH_INFO'])){ $pathinfo=array_filter(explode("/", $_SERVER['PATH_INFO'])); for($i=1;$i<=count($pathinfo);$i++){ $key=isset($pathinfo[$i]) ? $pathinfo[$i] : ''; $value=isset($pathinfo[$i+1]) ? $pathinfo[$i+1] :""; switch ($i) { case 1: $_GET['m']=ucfirst($key); break; case 2: $_GET['c']=ucfirst($key); break; case 3: $_GET['a']=$key; break; default: if($i>3){ if($i%2==0){ $_GET[$key]=$value; } } break; } } } $_GET['m']=!empty($_GET['m']) ? ucfirst($_GET['m']) : 'Index'; $_GET['c']=!empty($_GET['c']) ? ucfirst($_GET['c']) : 'Index'; $_GET['a']=!empty($_GET['a']) ? $_GET['a'] : 'index'; $class="\\Controller\\{$_GET['m']}\\{$_GET['c']}"; $controller=new $class; $controller->$_GET['a'](); } } Application::main();
\Controller\Index\Index.php
<?php namespace Controller\Index; use Service\User; class Index{ public function __construct(){ echo "构造方法<br/>"; } public function index(){ new User(); print_r($_GET); } public function login(){ echo "login()"; } }
效果:
相关文章
- [PHP] 504 Gateway Time-out处理流程
- [设计模式] 五种创建型设计模式特点
- [设计模式] 设计模式中的七大原则
- [MySQL] mysql 5.5和 5.6 timestamp default 默认值CURRENT_TIMESTAMP问题
- [前端系列] jquery的on事件实现hover函数效果
- [MySQL] mysql优化实例-delete数据不会减少数据文件大小
- [MySQL] mysql优化实例-为join表关联字段增加索引
- 侧边悬浮在线客服咨询按钮-在线客服按钮代码实现
- [前端系列] 解决默认样式-用户代理样式表问题
- [MySQL系列] mysql find_in_set搜索以逗号分隔的字符串
- [前端系列] 解决el-table导致TypeError: this.$el.querySelectorAll is not a function
- [MySQL] group by 分组并进行组内排序取得最新一条
- [PHP系列] popim 私有化独立部署即时通讯im系统搭建过程
- [前端系列]vue3修改模板变量间隔符
- 在线客服系统代码安装 (附移动版APP下载)
- [PHP] 装饰器模式-结构型设计模式
- [PHP] 数据映射器模式-结构型设计模式
- [PHP] 组合模式-结构型设计模式
- [前端系列] 解决Invalid prop: custom validator check failed for prop "type"
- [PHP] 桥接模式-结构型设计模式