首页 > 解决方案 > CakePHP 4 Middleware 返回 withStatus 并中断执行脚本

问题描述

路由.php

$routes->applyMiddleware('MyMiddleware');

应用程序.php

public function routes(\Cake\Routing\RouteBuilder $routes): void {
    $options = [
        'httponly' => true,
    ];
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware($options));
    
    $routes->registerMiddleware('MyMiddleware', new Middleware\MyMiddleware());
    parent::routes($routes);
}

src/Middleware/MyMiddleware.php

公共函数过程(ServerRequestInterface $request,RequestHandlerInterface $handler):ResponseInterface {

        $response = $handler->handle($request);
  
        返回 $response->withStatus(401,'Fail');
}

它正确响应 httpd 401 代码,但脚本继续工作,通过控制器和视图。

我想通过返回 200 以外的 http 代码来停止执行。在 cakephp 4 中不起作用。

有人可以告诉我如何返回 http 401 并破坏脚本。

标签: cakephp-4.x

解决方案


我发现它的唯一形式不使用方法过程,即使在 cakePHP 4 中我也使用了方法 __invoke,我可以得到预期的结果


推荐阅读