0

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

但我不太确定是否可以。你能给我一些想法如何改进它并摆脱重复的代码吗?

4

1 回答 1

1

您应该将该代码移动到服务中。像这样,您可以像这样访问您的方法:

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

与您当前方法相比的优势在于,您的所有代码逻辑都将存储在一个文件中。所以维护起来会更容易。你也不应该echoControllers. 改为呈现适当的模板或引发异常。对于您的情况,这HttpNotFoundException似乎是正确的选择。

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

创建一个expenseFinder.phpsrc/[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]

现在你可以按照我文章开头的描述来调用它。

于 2013-08-01T08:51:38.807 回答