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

Yii 框架設定預設 Controller 與 Action 完整指南

     編輯:PHP 相關知識

兩層級預設機制

Yii 透過「應用程式層級」與「控制器層級」雙重設定,彈性決定預設進入點。

1. 設定預設 Controller(應用程式層級)

檔案: /protected/config/main.php

<?php
return array(
    'name' => 'Auto',
    'defaultController' => 'auto',  // 對應 AutoController.php
);

此時訪問 index.php 將自動路由至 AutoController。

2. 設定預設 Action(控制器層級)

檔案: /protected/controllers/AutoController.php

class AutoController extends CController {
    public $defaultAction = 'test';  // 預設動作

    public function actionTest() {
        // 預設進入邏輯
    }
}

實際路由效果

訪問 URL實際路由說明
https://domain/index.phpindex.php?r=auto/test雙重預設生效
https://domain/index.php?r=autoindex.php?r=auto/test僅指定 Controller,Action 套用預設
https://domain/index.php?r=auto/indexindex.php?r=auto/index明確指定 Action,覆蓋預設

常見應用場景

  • 單頁應用入口:將 defaultController 指向 SPA 入口控制器
  • 模組預設頁面:模組內同樣支援 defaultController 設定
  • API 版本控制:不同版本模組各自設定預設動作

注意事項

  1. Controller 名稱在配置中使用小寫(auto 對應 AutoController)
  2. Action 方法必須為 public 且命名為 action* 格式
  3. 若 Controller 不存在,將拋出 404 而非套用預設

善用雙層預設機制,能讓 URL 更乾淨,也便於專案初期快速原型開發。

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