如何将实例注入容器
在某些应用中,您可能需要注入一个类实例作为服务,而不是配置容器来创建一个新的实例。
例如,Symfony 中的 kernel
服务是从 Kernel
类中注入到容器中的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// ...
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
abstract class Kernel implements KernelInterface, TerminableInterface
{
// ...
protected function initializeContainer(): void
{
// ...
$this->container->set('kernel', $this);
// ...
}
}
在运行时设置的服务称为合成服务。 必须配置此服务,以便容器在编译期间知道该服务存在(否则,依赖于 kernel
的服务将会收到“服务不存在”错误)。
为了做到这一点,请在您的服务定义配置中将服务标记为合成服务
1 2 3 4 5
# config/services.yaml
services:
# synthetic services don't specify a class
app.synthetic_service:
synthetic: true
现在,您可以使用 Container::set()
将实例注入容器中
1 2 3
// instantiate the synthetic service
$theService = ...;
$container->set('app.synthetic_service', $theService);
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。