代码重复 - Symfony2

时间:2013-08-01 08:35:27

标签: symfony code-duplication

我正在使用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;
    }

但我不太确定它没关系。你能否告诉我如何改进这个并摆脱重复的代码?

1 个答案:

答案 0 :(得分:1)

您应该将该代码移到service。像这样你可以像这样访问你的方法:

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

优于当前方法的优点是所有代码逻辑都将存储在一个文件中。所以保持它会更容易。此外,您永远不会使用echo内的Controllers方法。渲染适当的template或抛出异常。对于您的情况,HttpNotFoundException似乎是正确的选择。

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

expenseFinder.php中创建src/[Your Company]/[Your Bundle]/Util

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]

现在你可以按照帖子开头的描述来调用它。