ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 路由器 [TOC] http://localhost:8081/TestController/test 以上代码会先在/app/Controllers目录下寻找TestController控制器,如果没有再去/Server/Controllers目录下寻找,如果依旧没有找到将返回404界面。 test是方法名,它将和business.php Config中的 ```php $config['http']['method_prefix'] = 'http_'; ``` 合并成访问的方法名,默认前缀名为‘http_’,可以通过修改配置自己设置。 所以以上url会访问到/Server/Controllers下的TestController控制器的http_test方法并输出helloworld。 ```php <?php class TestController extends Controller { /** * http测试 */ public function http_test() { $this->http_output->end('helloworld',false); } } ``` ## 多级路由 默认的NormalRoute支持多级路由 http://localhost:8081/V1/TestController/test 可以在app/Controllers目录下添加V1目录,这样上面的URL将访问V1目录下的TestController类中的test方法。 可以添加更多级的文件夹。 ## 自定义路由 自定义路由需要实现以下几个方法 ```php interface IRoute { function handleClientData($data); function handleClientRequest($request); function getControllerName(); function getMethodName(); function getParams(); function getPath(); function errorHandle($e, $fd); } ``` 1.(仅仅TCP)handleClientData 设置反序列化后的数据 Object 2.(仅仅HTTP)handleClientRequest 处理http request 3.getControllerName 获取控制器名称 4.getMethodName 获取方法名称 5.(仅仅HTTP)getPath 获取url_path 6.(仅仅TCP)getParams 获取参数/扩展 解析错误的回调 ```php function errorHandle($fd) ``` 注意getParams是作为一个扩展,如果这里被返回了参数,那么这个参数会被直接当做调用Controller方法的传入参数。 ```php class ProtoController extends Controller { public function makeMessageData(AbstractMessage $responseMessage) { //这里的$responseMessage就是getParams()获取到的对象 } } ``` ## 自定义协议配置 route 举例 和 Pack 中的例子对应, 将不同 `msg_type` 的消息分发到控制器中不同的方法下 ```php namespace Server\Route; use Server\CoreBase\SwooleException; class GameRoute implements IRoute { // 其他方法都可以保持不变 /** * 获取控制器名称 * @return string */ public function getControllerName() { return 'GameController'; } /** * 获取方法名称 * @return string */ public function getMethodName() { $methodName = 'ping'; $msgType = $this->client_data->msg_type; if ($msgType == 2) { $methodName = 'pong'; } return $methodName. 'Msg'; } } ``` 这样, 不同类型的消息就分发到 `GameController` 下的对应 `method`, 使用 `$this->client_data` 即可获取到 `unpack` 后的数据