如何访问Slim v3中间件类中的$CONTAINER? [英] How to access the $container within middleware class in Slim v3?

查看:15
本文介绍了如何访问Slim v3中间件类中的$CONTAINER?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到在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')

这篇关于如何访问Slim v3中间件类中的$CONTAINER?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆