一、前言
MixPHP作者没有将路由这部分专门分配一个文件夹进行代码架构,都是放在config文件里面的,而因为MixPHP有多种模式(http模式、常驻同步、常驻协程),在多个配置之间切换,路由也需要迁移,有些麻烦,所以单独把路由拿出来进行单独管理。
二、具体操作
1. 在目标应用配置文件夹下添加route.php,此处示范地址:apps/api/config/route.php。
2. 填充路由文件
<?php
function route()
{
return
[
// 默认访问主页
'' => ['Index', 'Index'],
// 其他路由
'POST /api/user/login' => ['User', 'Login'],
'GET /api/user/info/:id' => ['User', 'Info', 'middleware' => ['Before']],
// 控制器/方法 路由
':controller/:action' => [':controller', ':action']
];
}
3. http_compatible.php、http_coroutine.php、http_permanent.php 引入路由文件,修改配置,如下示例:
<?php
// 引入路由函数文件
require __DIR__ . '/route.php';
// Apache/PHP-FPM 传统环境下运行的 HTTP 服务配置(传统模式)
return [
// 基础路径
'basePath' => dirname(__DIR__),
// 控制器命名空间
'controllerNamespace' => 'apps\api\controllers',
// 中间件命名空间
'middlewareNamespace' => 'apps\api\middleware',
// 全局中间件
'middleware' => [],
// 组件配置
'components' => [
// 路由
'route' => [
// 类路径
'class' => 'mix\http\Route',
// 默认变量规则
'defaultPattern' => '[\w-]+',
// 路由变量规则
'patterns' => [
'id' => '\d+',
],
// 路由规则
'rules' => route(), // 在这里引入路由函数
// URL后缀
'suffix' => '.html',
],
……
],
// 类库配置
'libraries' => [
],
];
完成以上配置,就可以共用路由文件了,以后在写路由的时候直接在route.php文件中操作。