gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:17:12 59 4
gpt4 key购买 nike

我一直在读到在 Slim v2 中,$app 被绑定(bind)到中间件类。我发现这不是 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 容器的正确方法是什么?我猜应该有办法吧?

最佳答案

晚会有点晚,但可能会帮助其他人......你必须在实例化中间件时注入(inject)你的容器

$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

}
}

乐:稍微扩展一下初始答案,容器得到 injected in the constructor如果您将中间件作为 string

类提供
$app->add('Auth');

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

关于php - 如何在 Slim v3 的中间件类中访问 $container?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34839399/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com