首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Zend Framework 動作助手 Redirector 完整用法指南

     編輯:PHP 綜合知識

Redirector 助手簡介

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。

實戰範例

範例 1:設定預設選項

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();
    }
}

範例 2:使用預設設定

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');
    }
}

範例 3:gotoSimple() 模擬 _forward()

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'
        ]);
    }
}

範例 4:gotoRoute() 路由組裝

// 假設已註冊路由 '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常見數據庫操作技巧匯總》。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved