繁体   English   中英

Symfony将所有捆绑软件参数注入DI服务

[英]Symfony Inject All Bundle Parameters into DI Service

我正在使用Symfony并试图创建一个服务,该服务包含在AppBundle的parameters.xml中设置的所有应用程序参数。

我上次通过将ServiceContainer注入Service并在其上使用-> get('param_name')来做到这一点,尽管我知道注入整个容器是一种非常糟糕的做法,但效果很好。

有没有一种方法可以将所有参数注入到服务中,而不必将每个参数作为arg添加到服务定义中?

上一个项目我实质上是这样做的

服务定义

<service id="myapp.application_parameters" class="AppBundle\DependencyInjection\Service\ApplicationParametersService">
    <argument type="service" id="service_container" />
</service>

和服务等级

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;
}

您是对的:在大多数情况下,容器的注入是反模式。 但是注入所有参数也是一种不好的做法:您不确切知道服务实际使用了哪些参数,因为它可以访问所有参数。 当代码仅获取其真正需要的值时,效果会更好。

如果这种方法可以接受,并且您只需要减少样板代码,则可以使用父服务或自动装配。

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)使用自动装配:

<service id="specific_service_a" class="..." autowire="true">

至少您可以通过全局变量获取容器。 最危险的方式,但是可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM