如何访问Slim v3中间件类中的$CONTAINER?

2022-06-13 00:00:00 php slim slim-3

我读到在Slim v2中,$app被绑定到中间件类。我发现在v3中不是这样的?以下是我的中间件类,但我只是不确定:

<?php
namespace CrSrcMiddleware;

class Auth
{
    /**
     * Example middleware invokable class
     *
     * @param  PsrHttpMessageServerRequestInterface $request  PSR7 request
     * @param  PsrHttpMessageResponseInterface      $response PSR7 response
     * @param  callable                                 $next     Next middleware
     *
     * @return PsrHttpMessageResponseInterface
     */
    public function __invoke($request, $response, $next)
    {
        // before

var_dump($this->getContainer()); // method undefined
var_dump($this->auth); exit; // method undefined
        if (! $this->get('auth')->isAuthenticated()) {
            // Not authenticated and must be authenticated to access this resource
            return $response->withStatus(401);
        }

        // pass onto the next callable
        $response = $next($request, $response);

        // after


        return $response;
    }
}
访问中间件中的DI容器的正确方式是什么?我猜应该有办法吧?


解决方案

聚会有点晚,但可能会对其他人有所帮助... 实例化中间件时必须注入容器

$container = $app->getContainer();
$app->add(new Auth($container));

您的中间件需要构造函数

<?php
namespace CrSrcMiddleware;

class Auth
{

    private $container;

    public function __construct($container) {
        $this->container = $container
    }

    /**
     * Example middleware invokable class
     *
     * @param  PsrHttpMessageServerRequestInterface $request  PSR7 request
     * @param  PsrHttpMessageResponseInterface      $response PSR7 response
     * @param  callable                                 $next     Next middleware
     *
     * @return PsrHttpMessageResponseInterface
     */
    public function __invoke($request, $response, $next)
    {
        // $this->container has the DI

    }
}
LE: 稍微扩展一下最初的答案,如果您将中间件作为类提供字符串

,容器将得到injected in the constructor
$app->add('Auth');

$app->add('Auth:similarToInvokeMethod')

相关文章