【问题标题】:Symfony Inject All Bundle Parameters into DI ServiceSymfony 将所有 Bundle 参数注入 DI 服务
【发布时间】:2017-06-03 15:59:39
【问题描述】:

我正在使用 Symfony 并尝试创建一个服务来保存我们在 AppBundle 中的 parameters.xml 中设置的所有应用程序参数。

我上次通过将 ServiceContainer 注入服务并在其上使用 ->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;
}

【问题讨论】:

    标签: php symfony dependency-injection parameters


    【解决方案1】:

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

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

    1) 与parent service:

    <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">
    

    至少你可以通过global variable 获取容器。最危险的方式,但它有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      相关资源
      最近更新 更多