2013-08-01 61 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