将变量传递给Symfony2服务构造函数


Passing variables to Symfony2 service constructor

我有一个Symfony2应用程序(到第三方API的桥梁),主要由控制台命令组成。每个控制台命令都有一个"organizationId"参数,用于解析API的各种选项,如API密钥、url、可用语言等。应用程序中90%的服务使用这些参数来调用API,或在本地数据库中获取/存储数据。

我使用Symfony DI来构建服务,每个服务都有公共方法setOrganization(Organization $organization),该方法在获得服务后调用。例如(简化代码):

protected function execute(InputInterface $input, OutputInterface $output)
{
    $organization = $this
        ->getContainer()
        ->get('doctrine')
        ->getRepository('CoreBundle:Organization')
        ->find($input->getArgument('organizationId'));
    $personService = $this->getContainer()
        ->get('person')
        ->setOrganization($organization); // I want to get rid of this
    $personService->doStuff();
}

服务定义:

person:
    class: AppBundle'Services'Person
    arguments: ["@buzz", "@doctrine.orm.entity_manager", "@organization_settings_resolver", "%media_service%"]

我正在寻找一种重构代码的方法,这样在使用任何服务时都不需要调用setOrganization()。是否可以在不传递整个服务容器的情况下将对象或命令行参数传递给构造函数?也许应该有一种不同的方法,例如security.token_storage层,它会以控制台的方式存储类似"会话信息"的东西?这里最好的建筑和Symfony方式解决方案是什么?

在服务定义中,您可以在初始化时调用服务的一个方法,这样您就可以避免在获得它后调用它:

person:
    class: AppBundle'Services'Person
    arguments: ["@buzz", "@doctrine.orm.entity_manager", "@organization_settings_resolver", "%media_service%"]
    calls:
        - [ setOrganization,[ @your_organization ] ]

如果您的组织是一个已定义且可用的服务

您可以将组织作为->doStuff()方法的参数吗?

这样,您就不需要再调用setOrganisation,也不需要在不首先设置组织的情况下调用doStuff。