php - 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 中使用配置方法,并在每个控制器的操作中调用它。但它并不那么优雅。
解决方案
您可以通过执行类似的操作来定义不同的实例(例如:具有不同的配置)
services:
App\Service\MyCustomService $s1:
config:
- foo: 'bar'
并注入控制器动作,如
public function action_1(MyCustomService $s1)
参数按名称匹配,每次您使用该签名(类名 + 参数名)定义参数时,Symfony 都会注入正确的实例。
您还应该将控制器设置autowire
和注册为服务
推荐阅读
- python - 如何使用python从本地网站获取数据
- python - 从邻接矩阵中绘制具有边权重的特定网络
- jquery - 如何使 jquery 数据表呈现的搜索框可访问?
- android - 无法构建发布应用程序,gradle 说找不到封闭方法'boolean onCreateOptionsMenu(android.view.Menu)
- python - 为什么形状不会在屏幕上移动?
- java - 在 JVM 中调试 100% CPU 使用率
- apache - Apache 2.4 如何仅重定向精确的 php 文件 - 但不是正常查询
- powershell - 如何在PowerShell中解析SQL结果
- sql - 在查询中将特定行添加在一起
- angular - Toast 消息在 Angular 项目中不起作用