2013-08-01 62 views
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; 
    } 

但我不太確定沒關係。你能給我一些想法如何改善這一點,擺脫重複的代碼?

回答

1

您應該將該代碼移動到service。就像你可以訪問你的方法是這樣的:在當前的方法

$expense = $this->get('expenseFinder')->findExpense($id); 

的好處是,你的所有代碼邏輯將被存儲在一個單一的文件。所以保持它會更容易。你也應該從來沒有在你的Controllers裏面使用echo方法。改爲渲染適當的template或引發異常。對於你的情況,HttpNotFoundException似乎是正確的選擇。

if(!$this->expense){ 
    throw new HttpNotFoundException(); 
} else { 
    return $this->expense = $this->expense[0]; 
} 

創建src/[Your Company]/[Your Bundle]/Util一個expenseFinder.php

class expenseFinder { 

    protected $em; 


    public function __construct(EntityManager $em) { 
     $this->em = $em; 
    } 

    public function findExpense($id) { 
     // your logic here... 
    } 

} 

並註冊在app/config/config.yml

services: 
    expenseFinder: 
     class: [Your Company]\[Your Bundle]\expenseFinder 
     arguments: [@doctrine.orm.entity_manager] 

服務現在在我的文章的開頭描述的,你可以調用它。

+0

非常感謝!但我不能userdstand如何使用這種方法:(如何將id作爲參數提供給服務(如果我必須給它)?並且有1-2個方法不需要它 - 接下來會發生什麼?然後,我應該在服務班上做些什麼:(對不起,我再次非常感謝你:) – Faery

+0

更新了我的答案。 – ferdynator