如果你想在中间件中有另一个中间件/对象,你必须使用像这样的工厂
namespace App\Somnething;
use Interop\Container\ContainerInterface;
class MyMiddlewareFactory
{
public function __invoke(ContainerInterface $container, $requestedName)
{
return new $requestedName(
$container->get(\App\Path\To\My\Middleware::class)
);
}
}
SoMyMiddleware
将被注入,\App\Path\To\My\Middleware
我们将能够访问它。
问题:将中间件注入应用程序本身或容器是否会出错?喜欢:
namespace App\Somnething;
use Interop\Container\ContainerInterface;
use Zend\Expressive\Application;
class MyMiddlewareFactory
{
public function __invoke(ContainerInterface $container, $requestedName)
{
return new $requestedName(
$container->get(Application::class)
);
}
}
这样就可以随时获得任何东西。喜欢
namespace App\Somnething;
use Zend\Expressive\Application;
class MyMiddleware
{
/** @var Application $app */
protected $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function __invoke($some, $thing)
{
if ($some and $thing) {
$ever = $this->app
->getContainer()
->get(\Path\To\What\Ever::class);
$ever->doSome();
}
}
}