如何从Symfony中的Service访问容器?

joe*_*oel 0 routing containers symfony

我已经创建了一个服务,并且想从内部访问容器,以便可以访问路由,我应该注入容器还是在调用该服务的控制器中处理该容器?

off*_*ite 5

人们普遍认为将容器注入任何东西是个坏主意。

在services.yml(或services.xml)中声明服务时,可以向其中注入其他服务:

your.awesome.service:
    class: Hippies\FlowerBundle\Service\Awesome
    arguments:
        - '@router'
Run Code Online (Sandbox Code Playgroud)

并处理您的服务类的构造函数:

public function __construct($router)
{
    $this->router = $router;
}
Run Code Online (Sandbox Code Playgroud)