Slim 3中如何在DI中配置中间件

How to configure middleware in DI in Slim 3

我想在Slim的Dependency Container中配置几个中间件,这样我就可以在同一个地方设置几个常量,方便地添加中间件。

例如

$configuration = [
    'settings' => [
        'displayErrorDetails' => true,
    ],
    'auth_settings' => [
        'serect' => 'garyAPIserver',
    ],
];
$container = new Slim\Container($configuration);
$container['auth'] = function ($c) {
    return new AuthMiddleware($c['auth_settings']);
};
$app = new Slim\App($container);

然后我尝试在 DI 中调用中间件:

$app->add($app->get('auth'));

我收到了 php 打印的警告消息:

Warning: Missing argument 2 for Slim\App::get(), called in E:\www\slimServer-3.0\index.php on line 12 and defined in E:\www\slimServer-3.0\vendor\slim\slim\Slim\App.php on line 146

Slim 打印的错误信息:

Type: RuntimeException
Message: is not resolvable
File: E:\www\slimServer-3.0\vendor\slim\slim\Slim\CallableResolver.php
Line: 82

我是Slim新手,DI里面可以设置中间件吗?有类似场景的攻略吗?

您可以使用 $container 变量:

$app->add($container->get('auth'));

然后您可以在路由器功能中使用它:

$auth = $this->get('auth');

查看here了解更多信息。