您现在的位置是:网站首页> 编程资料编程资料

PHP实现的简单路由和类自动加载功能_php技巧_

2023-05-25 534人已围观

简介 PHP实现的简单路由和类自动加载功能_php技巧_

本文实例讲述了PHP实现的简单路由和类自动加载功能。分享给大家供大家参考,具体如下:

项目目录如下

入口文件index.php

类自动加载文件environment.php

我这里类的加载规则是 比如core__app::run() 对应 根目录/core/app.php 的 run()方法,用到了spl_autoload_register()函数实现自动加载,当调用某个类名的时候,会自动执行spl_autoload_register('loader::load'),根据类名include对应的类文件。

app.php入口文件执行的方法开始跑框架流程

 1) { $controller = $params[0]; $method = $params[1]; } elseif ($count == 1) { $controller = 'index'; $method = $params[0]; } else { } $filename = WEBROOT . '/controller/' . $controller . '.php'; $controller = 'controller__'.$controller; try { if (!file_exists($filename)) { throw new Exception('controller ' . $controller . ' is not exists!'); return; } include($filename); if (!class_exists($controller)) { throw new Exception('class ' . $controller . ' is not exists'); return; } $obj = new ReflectionClass($controller); if (!$obj->hasMethod($method)) { throw new Exception('method ' . $method . ' is not exists'); return; } } catch (Exception $e) { echo $e; //展示错误结果 return; } $newObj = new $controller(); call_user_func_array(array($newObj, $method), $params); } } 

根据请求uri去找对应的controller, 用call_user_func_array()的方式调用controller里的方法

根目录/controller/test.php

这里其实调用不一定要调用model里的test方法,可以调model目录下的任意文件,在此之前可以去都读一些config文件等等操作。

根目录/model/test.php

例如hostname/test/write 这个请求就会从入口文件进来,经过core__app::run就会找到controller下对应的的controller__test类,执行write()方法

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

-六神源码网