怎么在PHP中实现路由和类自动加载功能?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
入口文件index.php
<?php
define('WEBROOT', 'C:/Users/Administrator/Documents/NetBeansProjects/test');
require_once(WEBROOT.'/core/environment.php');
core__app::run(); //
类自动加载文件environment.php
<?php
//根据类名来include文件
class loader {
//找到对应文件就include
static function load($name) {
$file = self::filepath($name);
if ($file) {
return include $file;
}
}
static function filepath($name, $ext = '.php') {
if (!$ext) {
$ext = '.php';
}
$file = str_replace('__', '/', $name) . $ext; //类名转路径
$path .= WEBROOT . '/' . $file;
if (file_exists($path)) {
return $path; //找到就返回
}
return null;
}
}
spl_autoload_register('loader::load');
我这里类的加载规则是 比如core__app::run()
对应 根目录/core/app.php 的 run()
方法,用到了spl_autoload_register()
函数实现自动加载,当调用某个类名的时候,会自动执行spl_autoload_register('loader::load')
,根据类名include对应的类文件。
app.php入口文件执行的方法开始跑框架流程
<?php
class core__app {
static function run() {
$a = $_SERVER['REQUEST_URI'];
$uri = rtrim(preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']), '/');
$params = explode('/', trim($uri, '/'));
$count = count($params);
if ($count > 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
<?php
class controller__test {
public function write($controller, $method) {
//config__test::load('test');
model__test::write($controller, $method);
}
}
这里其实调用不一定要调用model里的test方法,可以调model目录下的任意文件,在此之前可以去都读一些config文件等等操作。
根目录/model/test.php
<?php
class model__test {
public function write($model, $method) {
echo 'From controller:'.$model.' to model: ' . $model . ' ,method: ' . $method;
}
}
php是一个嵌套的缩写名称,是英文超级文本预处理语言,它的语法混合了C、Java、Perl以及php自创新的语法,主要用来做网站开发,许多小型网站都用php开发,因为php是开源的,从而使得php经久不衰。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。