当我扩展ContainerAware或实现ContainerAwareInterface时,服务不调用setContainer。
class CustomService implements ContainerAwareInterface
{
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
}
如何在没有注入的情况下使用服务中的容器?是否需要将容器对象传递给构造函数或setter?
6条答案
按热度按时间d4so4syb1#
在services.yml文件中进行定义
dfty9e192#
仅实现
ContainerAware
或ContainerAwareInterface
是不够的。您必须使用service_container
作为参数调用setter注入。**但不建议注入整个容器。**最好只注入您真正需要的服务。lf3rwulv3#
您必须将服务名称放在引号内:
fiei3ece4#
这是一个完整实现容器感知服务的示例。
**但请注意,应避免注入整个容器。**最佳做法是只注入所需的组件。有关此主题的更多信息,请参阅Law of Demeter - Wikipedia。
为此,此命令将帮助您找到所有可用的服务:
不管怎样,这是完整的例子。
app/config/services.yml
档案:src/AppBundle/Service/MyService.php
中的服务类:最后是
src/AppBundle/Controller/MyController.php
中的控制器:nbysray55#
您还可以使用ContainerAwareTrait来实现ContainerAwareInterface。
1u4esq0p6#
您可能希望在所有具有
ContainerAwareInterface
(基于this answer)的类上自动调用setContainer
: