[英]Symfony Inject All Bundle Parameters into DI Service
I am using Symfony and trying to create a service that holds all of the application parameters that we have set in our parameters.xml in our AppBundle. 我正在使用Symfony并试图创建一个服务,该服务包含在AppBundle的parameters.xml中设置的所有应用程序参数。
I did it last time by injecting the ServiceContainer into the Service and using ->get('param_name') on it which worked fine though I know that it is quite bad practice to inject the whole container. 我上次通过将ServiceContainer注入Service并在其上使用-> get('param_name')来做到这一点,尽管我知道注入整个容器是一种非常糟糕的做法,但效果很好。
Is there a way I can just get all parameters injected into my service without having to add them each as an arg to the service definition?? 有没有一种方法可以将所有参数注入到服务中,而不必将每个参数作为arg添加到服务定义中?
Last project I did this in essence 上一个项目我实质上是这样做的
Service Definition 服务定义
<service id="myapp.application_parameters" class="AppBundle\DependencyInjection\Service\ApplicationParametersService">
<argument type="service" id="service_container" />
</service>
And service class 和服务等级
namespace AppBundle\DependencyInjection\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ApplicationParametersService
{
private $_container;
protected $developmentEmail;
function __construct(ContainerInterface $container)
{
$this->_container = $container;
$this->developmentEmail = $this->_container->getParameter('myapp.dev.email');
}
public function getDevEmail()
{
return $this->developmentEmail;
}
You are right: injection of container is antipattern in most cases. 您是对的:在大多数情况下,容器的注入是反模式。 But injection of all parameters is a bad practice too: you don't know exactly what parameters are actually used by the service, because it has access to all of them.
但是注入所有参数也是一种不好的做法:您不确切知道服务实际使用了哪些参数,因为它可以访问所有参数。 It is better when the code gets only the values that it really needs.
当代码仅获取其真正需要的值时,效果会更好。
If this way is acceptable and you need to just reduce a boilerplate code, then you can use a parent service or the autowiring. 如果这种方法可以接受,并且您只需要减少样板代码,则可以使用父服务或自动装配。
1) With parent service : 1)与父母服务 :
<service id="generic_service" abstract="true">
<!-- it's better than whole container -->
<argument type="service" id="myapp.application_parameters"/>
</service>
<service id="specific_service_a" class="..." parent="generic_service"/>
<service id="specific_service_b" class="..." parent="generic_service"/>
2) With autowiring: 2)使用自动装配:
<service id="specific_service_a" class="..." autowire="true">
At least you can get the container through a global variable . 至少您可以通过全局变量获取容器。 Most risky way, but it works.
最危险的方式,但是可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.