你$this->redirect();
调用创建一个RedirectResponse
对象(API reference)。只有当您的控制器实际返回此对象时才会发生重定向。
return $this->redirect($this->generateUrl('someRoute'));
只是检查你的函数返回;)
use Symfony\Component\HttpFoundation\RedirectResponse;
public function someAction ($value)
{
$a = $this->myFunction($value);
if($a instanceof RedirectResponse) return $a;
// You won't come here if something wrong with $value
}
不过,我觉得这是最适合你用别的东西作为返回值:instanceof
是不漂亮。例如,如果出现错误,C例程通常返回-1。你可以做同样的事情,使用NULL也许是:
public function myFunction ($value)
{
if ($value == '')
{
return NULL; // Or something else (as long as it is illogical for your function to return it).
}
return 10;
}
public function someAction ($value)
{
$a = $this->myFunction($value);
if(is_null($a)) return $this->redirect($this->generateUrl('someRoute'));
// You won't come here if something wrong with $value
}
注:如果你想myFunction
路线的确定,只是用不同的返回值(负数也许?),并使其符合路线回你控制器(如果myFunction
返回-1,则转到route1
,如果返回-2,则转到route2
,依此类推)。您也可以使其返回路线本身(请检查is_string($a)
以查看myFunction
是否返回路线)。
你可能会让myFunction抛出一个异常。我想如果你真的想要你可以使用PHP头部命令并退出。不建议。底线:你需要调整一下你的想法。 @White有正确的方法。 – Cerad