【发布时间】:2016-01-20 14:07:13
【问题描述】:
我遇到了分解复杂控制器的问题。
动作有许多不同的条件,每个块内的代码使用不同的依赖关系。将其分解为单独的控制器的最合乎逻辑的方法是什么,以便我更好地处理不断增长的构造函数依赖项列表?
这一切都在一个动作中的原因是因为它提供一个 URL /report,它根据权限和其他条件呈现不同的模板。
附言。该代码在技术上不正确,是为了可视化我的问题而快速制作的。
<?php
class ExampleController
{
protected $dependency1;
protected $dependency2;
protected $dependency3;
protected $user;
/**
* ExampleController constructor.
*
* @param $dependency1
* @param $dependency2
* @param $dependency3
* @param $user
*/
public function __construct($dependency1, $dependency2, $dependency3, $user)
{
$this->dependency1 = $dependency1;
$this->dependency2 = $dependency2;
$this->dependency3 = $dependency3;
$this->user = $user;
}
public function exampleAction()
{
if ($this->user->hasRole('a')) {
$this->dependency1->something();
} elseif ($this->user->hasRole('b')) {
$this->dependency2->something();
} elseif ($this->user->hasRole('c')) {
$this->dependency3->something();
}
}
}
【问题讨论】:
-
你的控制器已经是服务了吗?您究竟如何将依赖项注入
__construct? -
是的,这就是您如何将依赖项注入到服务容器中定义的任何其他类中。
标签: php symfony controller dependencies