如果你想在中间件的另一中间件/对象 你必须使用一个工厂一样Zend的表现依赖注入
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)
);
}
}
所以MyMiddleware
将被注射了\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)
);
}
}
这样就可以得到任何东西〜在飞行中。 Like
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();
}
}
}
通过MiddlewareInterface实现Action中间件并让':: canCreate'检查是否返回in_array('MiddlewareInterface',class_implements($ requestedName),true);'谢谢btw! – cottton
这也是可以的。但据我所知,使用Reflection的代价非常昂贵。我不想自动初始化所有中间件,每个请求只有1个动作类对我来说就足够了。 – xtreamwayz