为什么这个函数没有返回值? - Symfony2

时间:2012-09-14 07:12:19

标签: symfony doctrine-orm

在我的控制器的操作中,我经常通过其id从数据库中的表中选择一行,因此我将其分离为一个函数。但是每当我这样做时,我会检查查询是否返回了某些内容,所以我也希望将它与函数分开。这是我的代码:

此功能在Controller中,由我的控制器扩展,其中包括以下操作:

protected function findById($id, $class)
{
    $result = $this->getEM()->getRepository('EMMyFriendsBundle:'.$class)->find($id);   
    if($result == null) {
        return false;
    } else {
        return $result;
    }
}

这是我的控制器:

class FriendController extends Controller
{
    private $em;
    private $friend;

    private function init($id)
    {
        $this->em = $this->getEM();
        $this->friend = $this->findById($id, 'Friend');

        if(!$this->friend) {
            return $this->render('EMMyFriendsBundle:Friend:error.html.twig', array(
               'item' => 'friend'));
        }   
    }

    /*
     * Displays all the information about a concrete friend
     */
    public function displayAction($id)
    {
        $this->init($id); 

        if($this->friend->getCategory() != null) {
            $category = $this->friend->getCategory()->getName();
        } else {
            $category = null;
        }

        return $this->render('EMMyFriendsBundle:Friend:friend.html.twig', array(
               'friend' => $this->friend, 'category' => $category));
    }

    // ...
}

当我选择一个不存在的ID(如38743874)时,它会转到init函数中的if-part,但不会呈现模板error.html.twig :(但如果我选择此部分

if(!$this->friend) {
                return $this->render('EMMyFriendsBundle:Friend:error.html.twig', array(
                   'item' => 'friend'));
            } 

init()函数中的

并在调用displayAction($id)之后将其放入$this->init($id),它可以正常工作。但我不想在该控制器的每一个动作中写这个。有任何想法如何分开它以避免代码重复?

1 个答案:

答案 0 :(得分:2)

您不会返回init函数的响应。这就是为什么它会向您显示错误消息。您必须在displayAction()中执行类似的操作:

$response = $this->init();
if ($response) {
    return $response;
}
相关问题