我正在使用 Symfony2 和 Doctrine,并且在我的控制器的几乎所有方法中都有几行重复。
他们来了:
$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;
}
但我不太确定是否可以。你能给我一些想法如何改进它并摆脱重复的代码吗?