【问题标题】:Is the process() function of cakePHP supposed to run more than once?cakePHP 的 process() 函数是否应该运行多次?
【发布时间】:2020-04-14 06:53:40
【问题描述】:

使用 cakePHP 中间件,我注意到函数 process() 可能会运行不止一次。从日志文件中可以看出。我不确定这是否会产生副作用。下面的例子:

class FooMiddleware implements MiddlewareInterface
{
    use LogTrait;


    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface
    {

        $this->log('Repeat?');  
        return $handler->handle($request);  
    }
}

在我的日志中,我得到了相同的时间戳。

2020-04-13 23:15:21 Error: Repeat?
2020-04-13 23:15:21 Error: Repeat?

这是预期的吗?

编辑

$middlewareQueue
        // Catch any exceptions in the lower layers,
        // and make an error page/response
        ->add(new ErrorHandlerMiddleware(Configure::read('Error')))

        // Handle plugin/theme assets like CakePHP normally does.
        ->add(new AssetMiddleware([
            'cacheTime' => Configure::read('Asset.cacheTime'),
        ]))

        // Add routing middleware.
        // If you have a large number of routes connected, turning on routes
        // caching in production could improve performance. For that when
        // creating the middleware instance specify the cache config name by
        // using it's second constructor argument:
        // `new RoutingMiddleware($this, '_cake_routes_')`
        ->add(new RoutingMiddleware($this))
        ->add($csrf)
        ->add(new AuthenticationMiddleware($this))
        ->add(new FooMiddleware())
        ->add(new AuthorizationMiddleware($this));

        if (Configure::read('debug')) {
            // Disable authz for debugkit
            $middlewareQueue->add(function ($req, $res, $next) {
                if ($req->getParam('plugin') === 'DebugKit') {
                    $req->getAttribute('authorization')->skipAuthorization();
                }
                return $next($req, $res);
            });
        }

    return $middlewareQueue;

【问题讨论】:

    标签: cakephp middleware


    【解决方案1】:

    不,它不应该运行多次,除非它多次包含在中间件队列中。

    做一些额外的调试来弄清楚发生了什么,例如记录堆栈跟踪:

    $this->log(\Cake\Error\Debugger::trace());
    

    也可以登录webroot/index.php:

    \Cake\Log\Log::write(\Psr\Log\LogLevel::ERROR, 'index.php hit');
    

    这应该显示中间件是否被多次调用(以及从何处调用),或者它是否实际上是多个请求。

    【讨论】:

    • webroot/index.php 也获得了两次“index.php hit”。我的中间件队列调用我的中间件一次。已编辑的问题。
    • @back2back 所以你可能有多个请求。检查您的浏览器脚本和网络控制台以找出可能的原因。也许有重定向,也许你正在做一个跨域请求导致发出预检请求,也许因为缺少编码信息而需要重新加载(Firefox 喜欢这样做),也许是美宝莲。
    • 在我的日志堆栈跟踪中,我可以看到中间件队列被调用,但我怀疑这两个调用 Cake\Http\Runner::run() - CORE/src/Http/Runner.php,第 58 行Cake\Http\Server::run() - CORE/src/Http/Server.php,第 90 行
    猜你喜欢
    • 1970-01-01
    • 2015-07-08
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2013-05-28
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多