企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 创建core/Controller.php ``` <?php namespace core; class Controller { protected $middleware = []; // 获取中间件 public function getMiddleware() { return $this->middleware; } // 调用控制器方法 为了不限制参数 // 所以方法设不设置$request 都无所谓 public function callAction($method, $parameters) { return call_user_func_array([$this, $method], $parameters); } } ``` ## 创建app/controller/UserController.php ``` <?php namespace App\controller; use App\middleware\ControllerMiddleWare; use core\Controller; use core\request\RequestInterface; // 继承基础控制器 class UserController extends Controller { protected $middleware = [ // 这个控制器的中间件 ControllerMiddleWare::class ]; public function index(RequestInterface $request) { return [ 'method' => $request->getMethod(), 'url' => $request->getUri() ]; } public function index2() { } } ``` ## 编辑core/RouteCollection.php的dispatch方法 ``` // 根据request执行路由 public function dispatch(RequestInterface $request) { $method = $request->getMethod(); $uri = $request->getUri(); $this->route_index = $method . $uri; $route = $this->getCurrRoute(); if(! $route) return 404; $middleware = $route['action']['middleware'] ?? []; $routerDispatch = $route['action']['uses']; if(! $route['action']['uses'] instanceof \Closure){ // 不是闭包 就是控制器了 $action = $route['action']; $uses = explode('@',$action['uses']); $controller = $action['namespace'].'\\'.$uses[0]; // 控制器 $method = $uses[1]; // 执行的方法 $controllerInstance = new $controller; $middleware = array_merge($middleware,$controllerInstance->getMiddleware()); // 合并控制器中间件 $routerDispatch = function ($request) use($route, $controllerInstance, $method){ return $controllerInstance->callAction($method,[ $request ]); }; } return \App::getContainer()->get('pipeline')->create()->setClass( $middleware )->run($routerDispatch)($request); } ``` ## 测试下 ### 创建app\middleware\ControllerMiddleWare.php 因为`UserController` 调用 这个中间件,所以要创建。 ``` <?php namespace App\middleware; use core\request\RequestInterface; class ControllerMiddleWare { public function handle(RequestInterface $request, \Closure $next) { echo "<hr/>controller middleware<hr/>"; return $next($request); } } ``` ### 运行 ![](https://img.kancloud.cn/97/af/97af9082e06d49664711b2abe6bafd58_606x133.png)![](https://img.kancloud.cn/f5/a4/f5a4822f5712c514f5af82f8d7d33fc4_690x290.png)