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