Zend_Controller_Action_Helper_Redirector 提供比 _redirect() 更強大的重導向功能,支援預先配置全站行為、使用類似 _forward() 的 gotoSimple() 介面,並能靈活控制 HTTP 狀態碼、退出行為、基礎 URL、絕對 URI 等。
setCode($code):設定 HTTP 重導向狀態碼(預設 302)。setExit($flag):重導向後是否強制 exit()(預設 true)。setGotoSimple($action, $controller, $module, $params):設定預設簡易 URL。setGotoRoute($urlOptions, $name):設定基於路由組裝的 URL。setGotoUrl($url):設定預設 URL 字串。setPrependBase($flag):是否在相對 URL 前加入基礎 URL。setUseAbsoluteUri($flag):強制使用絕對 URI(含 Host、Port、HTTPS)。gotoSimple():使用簡易 API 重導向。gotoRoute():使用路由組裝重導向。gotoUrl():使用 URL 字串重導向。redirectAndExit():重導向並立即退出。getRedirectUrl():取得目前設定的重導向 URL。class SomeController extends Zend_Controller_Action {
protected $_redirector = null;
public function init() {
$this->_redirector = $this->_helper->getHelper('Redirector');
$this->_redirector->setCode(303)
->setExit(false)
->setGotoSimple('this-action', 'some-controller');
}
public function myAction() {
// ... 業務邏輯
$this->_redirector->redirectAndExit();
}
}
class AlternativeController extends Zend_Controller_Action {
protected $_redirector = null;
public function init() {
$this->_redirector = $this->_helper->getHelper('Redirector');
}
public function myAction() {
$this->_redirector->gotoUrl('/my-controller/my-action/param1/test/param2/test2');
}
}
class ForwardController extends Zend_Controller_Action {
protected $_redirector = null;
public function init() {
$this->_redirector = $this->_helper->getHelper('Redirector');
}
public function myAction() {
$this->_redirector->gotoSimple('my-action', 'my-controller', null, [
'param1' => 'test', 'param2' => 'test2'
]);
}
}
// 假設已註冊路由 'blogArchive'
$route = new Zend_Controller_Router_Route(
'blog/:year/:month/:day/:id',
['controller' => 'archive', 'module' => 'blog', 'action' => 'view']
);
$router->addRoute('blogArchive', $route);
// 控制器中
$this->_redirector->gotoRoute([
'year' => 2006, 'month' => 4, 'day' => 24, 'id' => 42
], 'blogArchive');
// 產生 /blog/2006/4/24/42
原始碼展示了核心實現:_redirect() 組合完整 URI、設定 Location 標頭、處理 Session 關閉與腳本退出。__call() 提供舊版 API 相容性。
更多 Zend Framework 相關教程請參考本站專題:《Zend FrameWork框架入門教程》、《php優秀開發框架總結》、《Yii框架入門及常用技巧總結》、《ThinkPHP入門教程》、《php面向對象程序設計入門教程》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》。