如何解决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 都会注入正确的实例。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。