为什么此函数不返回值?-Symfony2
在我的控制器的操作中,我经常通过id从数据库中的表中选择一行,所以我将其分离为一个函数。但每次执行此操作时,我都会检查查询是否返回了某些内容,因此我也想将其与函数分开。这是我的密码: 此功能位于控制器中,由我的控制器扩展,其中包括以下操作:为什么此函数不返回值?-Symfony2,symfony,doctrine-orm,Symfony,Doctrine Orm,在我的控制器的操作中,我经常通过id从数据库中的表中选择一行,所以我将其分离为一个函数。但每次执行此操作时,我都会检查查询是否返回了某些内容,因此我也想将其与函数分开。这是我的密码: 此功能位于控制器中,由我的控制器扩展,其中包括以下操作: protected function findById($id, $class) { $result = $this->getEM()->getRepository('EMMyFriendsBundle:'.$class)->fin
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部分,但不会呈现模板error.html.twig:但是如果我选择这个部分
if(!$this->friend) {
return $this->render('EMMyFriendsBundle:Friend:error.html.twig', array(
'item' => 'friend'));
}
在调用$this->init$id之后,它就可以工作了。但我不想在控制器的每一个动作中都写下这句话。您知道如何将其分离以避免代码重复吗?您不返回init函数的响应。这就是为什么它会显示错误消息。您必须在displayAction中执行类似的操作:
$response = $this->init();
if ($response) {
return $response;
}