redirectToRoute必須由控制器操作返回才能工作。例如:Symfony2 redirectToRoute無返回
function testAction() {
return $this->redirectToRoute('homepage');
}
但是怎麼可能在動作函數外(從另一個函數)調用重定向?像:
function checkError() {
$this->redirectToRoute('error');
}
redirectToRoute必須由控制器操作返回才能工作。例如:Symfony2 redirectToRoute無返回
function testAction() {
return $this->redirectToRoute('homepage');
}
但是怎麼可能在動作函數外(從另一個函數)調用重定向?像:
function checkError() {
$this->redirectToRoute('error');
}
redirectToRoute()將始終需要返回,因爲它實際上是將響應發送到觸發重定向的瀏覽器。如果沒有從其中包含redirectToRoute()調用的方法返回任何內容,則重定向不會返回到瀏覽器,也不會發生重定向。
控制器必須返回響應。沒有辦法(幾乎)避免它。
您可以做的是在內部函數中使用異常,捕獲控制器中的異常並從控制器返回響應。防爆。
function testAction() {
try {
checkError();
} catch(Exception $e) {
return $this->redirectToRoute('error');
}
$this->redirectToRoute('success');
}
然後在您的checkError()
函數中拋出異常。
function checkError() {
throw new Exception();
}
這是一個基本情況。還有更多advanced ways to handle exceptions in Symfony2,還有more advanced ways of throwing exceptions。
這個函數是在父類的內部定義的。我從多個控制器操作中調用它。這不是在每個操作中檢查它的更好方法嗎? –
然後我會建議使用我已經找到答案的鏈接中的方法。通過處理kernel.exception,你可以在需要的地方重定向用戶。用可存儲響應的類擴展標準異常。在你的函數中拋出異常並將其設置爲事件處理函數中的$ event-> setResponse()。 – Stepashka
爲什麼不去做這樣的:
public function testAction() {
if (checkError()) {
return $this->redirectToRoute('homepage');
} else {
// return normal response
}
}
private function checkError() {
//test something
if ($error) return true; //I know I could just return $error
return false; //just making this clear
}
它不會作出任何意義,做到這一點。 'redirectToRoute'返回一個'RedirectResponse'對象,你必須對該對象做些什麼,本身在你的方法中「浮動」是無用的。也許你可以解釋爲什麼你(認爲你)需要這個? – Oldskool