0
我正在使用Symfony2和Doctrine,我在我的控制器的几乎所有方法中都有几行重复。代码重复 - Symfony2
在这里,他们是:
$this->expense = $this->expenseRepository->findByExpenseId($id);
if(!$this->expense){
echo 'There is no expense with such id...';
//redirect to error page
} else {
return $this->expense = $this->expense[0];
}
我想不出更好的方式来避免它比这
private function findExpense($id)
{
$this->expense = $this->expenseRepository->findByExpenseId($id);
if(!$this->expense){
return $this->redirect .... ;
} else {
return $this->expense = $this->expense[0];
}
}
,然后在每一个方法是这样的:
$expense = $this->findExpense($id);
if (!$expense) {
return $expense;
}
但我不太确定没关系。你能给我一些想法如何改善这一点,摆脱重复的代码?
非常感谢!但我不能userdstand如何使用这种方法:(如何将id作为参数提供给服务(如果我必须给它)?并且有1-2个方法不需要它 - 接下来会发生什么?然后,我应该在服务班上做些什么:(对不起,我再次非常感谢你:) – Faery
更新了我的答案。 – ferdynator