0

我使用Zend Expressive作为 API。我已经成功添加了一个中间件,它为每个请求验证 API 密钥的请求标头。

目前我使用 config/pipeline.php 中的 pipe() 函数添加中间件

$app->pipe(new MyAuthMiddleware(....);

这实际上工作得很好。但是,我想使用 Zend Servicemanager 添加管道,而不是使用配置文件,例如:

return [
'dependencies' => [
    /* ... */
    'invokables' => [
        // Remove this entry:
        App\Action\HelloAction::class => App\Action\HelloAction::class,
    ],
    'factories' => [
        /* ... */
        // Add this:
        App\Action\HelloAction::class => App\Action\HelloActionFactory::class,
    ],
    /* ... */
],];

问题:是否可以使用 Zend Servicemanager 管理中间件?如果是的话。

4

1 回答 1

4

是的,这是可能的。直到富有表现力的 1.1,它都是按照您的要求进行配置驱动的。从 1.1 开始,如果您通过骨架安装,默认情况下它是程序驱动的。你仍然可以使用配置驱动,但我不得不提到你不能同时使用两者。至少,不推荐。

配置可能看起来像这样(取自一个富有表现力的 1.0 表现力应用程序)。错误处理在 1.1+ 中发生了变化,但我没有一个例子。

<?php

return [
    'dependencies' => [
        'factories'  => [
            // ...
        ],
    ],

    'middleware_pipeline' => [
        'always' => [
            'middleware' => [
                Zend\Expressive\Helper\ServerUrlMiddleware::class,
            ],
            'priority'   => 10000,
        ],

        'routing' => [
            'middleware' => [
                Zend\Expressive\Container\ApplicationFactory::ROUTING_MIDDLEWARE,
                Zend\Expressive\Helper\UrlHelperMiddleware::class,
                LocalizationMiddleware::class,
                AuthenticationMiddleware::class,
                AuthorizationMiddleware::class,
                Zend\Expressive\Container\ApplicationFactory::DISPATCH_MIDDLEWARE,
            ],
            'priority'   => 1,
        ],

        'error' => [
            'middleware' => [
                Application\Middleware\Auth\UnauthorizedErrorMiddleware::class,
                Application\Middleware\Auth\ForbiddenErrorMiddleware::class,
                Application\Middleware\Logger\ExceptionLoggerMiddleware::class,
            ],
            'error'      => true,
            'priority'   => -10000,
        ],
    ],
]; 

这是我现在可以找到的更多信息:

于 2017-10-23T08:50:57.700 回答