继续上一章讲到了
<?php
// 路由初始化
$this->routeInit();
开发手册:https://www.kancloud.cn/manual/thinkphp5_1/353962
route
目录下的任何路由定义文件都是有效的,默认的路由定义文件是route.php
,但你完全可以更改文件名,或者添加多个路由定义文件(你可以进行模块定义区分,但最终都会一起加载)。routeInit方法会扫描route目录下的所有文件,将其include进来
/**
* 路由初始化 导入路由定义规则
* @access public
* @return void
*/
public function routeInit()
{
// 路由检测
$files = scandir($this->routePath);
foreach ($files as $file) {
if (strpos($file, '.php')) {
$filename = $this->routePath . $file;
// 导入路由配置
$rules = include $filename; // 如果$rules不是数组,那么include返回值是int(1),失败返回false
if (is_array($rules)) {
$this->route->import($rules);
}
}
}
if ($this->route->config('route_annotation')) {
// 自动生成路由定义
if ($this->appDebug) {
$suffix = $this->route->config('controller_suffix') || $this->route->config('class_suffix');
$this->build->buildRoute($suffix);
}
$filename = $this->runtimePath . 'build_route.php';
if (is_file($filename)) {
include $filename;
}
}
}
从代码说起:
在路由文件中定义下面的路由规则,使用门面模式调用Route类下的get方法
// routeroute.php
<?php
//Route::get('think', function () {
// return 'hello,ThinkPHP5!';
//});
// :对应动态参数
Route::get('hello/:name', 'index/hello');
// 上面的写法等同于
//Route::rule('hello/:name', 'index/hello', 'get');
// 可选参数
//Route::get('blog/:year/[:month]','Blog/archive');
// ...
// 更多使用方法看手册
这里以Route::get('hello/:name','index/hello');为测试用例进行代码分析,贴出每一步代码执行对应的值,复习的时候看看注释就好。
// thinkphp/library/think/Route.php
<?php
/**
* 注册GET路由
* @access public
* @param string $rule 路由规则
* @param mixed $route 路由地址
* @param array $option 路由参数
* @param array $pattern 变量规则
* @return RuleItem
*/
public function get($rule, $route