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

2022-08-30 22:02:13

我一直在阅读Slim v2中,$app被绑定到中间件类。我发现在v3中情况并非如此?下面是我的中间件类,但我只是没有定义:

<?php
namespace CrSrc\Middleware;

class Auth
{
    /**
     * Example middleware invokable class
     *
     * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
     * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
     * @param  callable                                 $next     Next middleware
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    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 容器的正确方法是什么?我猜应该有办法吗?


答案 1

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

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

您的中间件需要一个构造函数

<?php
namespace CrSrc\Middleware;

class Auth
{

    private $container;

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

    /**
     * Example middleware invokable class
     *
     * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
     * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
     * @param  callable                                 $next     Next middleware
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function __invoke($request, $response, $next)
    {
        // $this->container has the DI

    }
}

LE:稍微扩展一下初始答案,如果将中间件作为类字符串提供,则容器会注入构造函数中

$app->add('Auth');

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

答案 2

据我所知,Slim (v3) 的工作方式如下:

  • 如果将闭包作为中间件传递,则它使用容器作为参数进行调用。bindTo
  • 如果传递解析为类的类/字符串,则 Slim 将创建实例并将容器作为参数传递给构造函数

    <?php
    $app->add(Auth);
    
  • 否则(例如,如果您添加之前创建的中间件实例),那么看起来您必须负责传递所有必要的引用。


推荐