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

CodeIgniter _remap() 方法詳解:自訂路由規則與權限控制實戰

     編輯:PHP 相關知識

_remap() 核心機制

CodeIgniter 預設依 URI 第二段決定呼叫 Controller 方法:example.com/index.php/blog/comments/ → Blog::comments()。

若 Controller 定義 _remap(),所有 URI 規則失效,統一導向 _remap(),開發者自行決定呼叫哪個方法,實現「方法級路由重寫」。

public function _remap() {
    // 所有請求進入此處
}

應用場景一:隱藏真實方法名(URL 美化)

原 URL:/blog/display_successful_message
目標 URL:/blog/successful

public function _remap($method) {
    if ($method === 'successful') {
        $this->display_successful_message();
    } else {
        $this->$method(); // 其他方法正常呼叫
    }
}

應用場景二:方法級權限控制

public function _remap($method, $params = []) {
    $user_type = $_SESSION['user_type'] ?? 'guest';
    $access_control = $this->validate_access($user_type, $method);

    if ($access_control) {
        // 使用 call_user_func_array 支援參數傳遞
        call_user_func_array([$this, $method], $params);
    } else {
        $this->show_message('權限不足', 'error');
    }
}

private function validate_access($user_type, $method) {
    $rules = [
        'admin' => ['*'],
        'editor' => ['create', 'edit', 'view'],
        'guest' => ['view'],
    ];
    $allowed = $rules[$user_type] ?? [];
    return in_array('*', $allowed) || in_array($method, $allowed);
}

進階用法:參數解析與預設動作

public function _remap($method, $params = []) {
    // 預設動作
    if (empty($method)) {
        $method = 'index';
    }

    // 方法存在性檢查
    if (!method_exists($this, $method)) {
        show_404();
        return;
    }

    // 前置攔截:日誌、CSRF、速率限制等
    $this->before_action($method);

    // 呼叫目標方法
    call_user_func_array([$this, $method], $params);

    // 後置處理
    $this->after_action($method);
}

注意事項

  • _remap() 接收兩個參數:$method (URI 第二段)、$params (剩餘段落陣列)
  • 若需保留預設路由行為,可在 _remap() 內手動派發
  • 搭配 _output() 可進一步統一輸出格式 (JSON/XML/HTML)
  • 過度使用會降低程式碼可讀性,建議僅於跨領域關注點 (權限、日誌、多語系) 使用

摘自 jackyrong

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