我的控制器中有 init() 方法,如下所示:
class MyController extends GlobalController
{
private function init()
{
$this->setVariables($first = false, $second = true); // this comes from GlobalController
$this->bill_repository = $this->setRepository('Bill');
$this->var = .....;
....
}
...
}
和 GlobalController 是这样的:
class GlobalController extends BaseController
{
//Frequently used variables
protected $user;
protected $em;
protected $expense_repository;
protected function setVariables($first, $second)
{
$this->user = $this->container->get('security.context')->getToken()->getUser();
if($first){
$this->em = $this->getDoctrine()->getEntityManager();
}
if($second){
$this->expense_repository = $this->setRepository('Expense');
}
}
}
如何使用服务改善这一点?阅读 Symfony 的文档后我得到的理解是,我应该将这两个控制器都定义为服务和类似这样的东西:
<service id="my_controller" class="path/MyController" />
<service id="mycontroller_manager" class="path/GlobalController">
<call method="setVariables">
<argument type="???" id="???" />
</call>
</service>
但我不太确定这一点,也不太确定如何填写参数部分,或者我应该使用属性注入?请帮助我更好地理解这一点并改进我的代码:(