首页 > 解决方案 > Symfony 4 依赖注入 - 根据用例定义构造函数参数

问题描述

我有一个通用服务,它使用配置进行处理。

<?php

namespace App\Service;

class MyCustomService
{
    /**
     * @var array
     */
    private $config;

    /**
     * MyCustomService constructor.
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config = $config;
    }

    public function getConfig()
    {
        return $this->config;
    }
}

我想将该服务注入到控制器的操作中。但是每个动作都有一个特定的配置。

<?php

namespace App\Controller;

use App\Service\MyCustomService;

class MyCustomController
{
    public function action_1(MyCustomService $myCustomService)
    {
        /**
         * $config must contain 
         * ['foo' => 'bar']
         */
        $config = $myCustomService->getConfig();
    }

    public function action_2(MyCustomService $myCustomService)
    {
        /**
         * $config must contain
         * ['foo' => 'baz']
         */
        $config = $myCustomService->getConfig();
    }
}

我怎样才能做到这一点config/services. Yaml

有没有办法配置控制器操作?

像这样,例如:

services: 
    #...
    #...
    #...
        
    App\Controller\MyCustomController:action_1:
        arguments:
            $myCustomService: 
                App\Service\MyCustomService:
                    arguments:
                        $config: {foo: 'bar'}
        
    App\Controller\MyCustomController:action_2:
        arguments:
            $myCustomService: 
                App\Service\MyCustomService:
                    arguments:
                        $config: {foo: 'baz'}

我可以在 MyCustomService 中使用配置方法,并在每个控制器的操作中调用它。但它并不那么优雅。

标签: phpsymfonydependency-injectionsymfony4

解决方案


您可以通过执行类似的操作来定义不同的实例(例如:具有不同的配置)

services:
 App\Service\MyCustomService $s1:
  config: 
    - foo: 'bar'

并注入控制器动作,如

public function action_1(MyCustomService $s1)

参数按名称匹配,每次您使用该签名(类名 + 参数名)定义参数时,Symfony 都会注入正确的实例。

您还应该将控制器设置autowire注册为服务


推荐阅读