yii\base\Module 是所有模組與應用程式(Application)的基類,定義了模組的生命週期、屬性配置、子模組管理、控制器對應、視圖路徑解析等核心功能。本文節選關鍵原始碼並加註解析。
| 屬性 | 型別 | 說明 |
|---|---|---|
| $id | string | 模組唯一 ID,用於區分同父模組下的子模組 |
| $module | Module|null | 父模組實例,頂層為 null |
| $controllerNamespace | string | 控制器類別命名空間,預設為 模組命名空間\controllers |
| $controllerMap | array | 控制器 ID 到類別配置的映射,支援字串或陣列配置 |
| $defaultRoute | string | 預設路由,預設 default(對應 DefaultController::actionIndex) |
| $layout | string|bool | 佈局視圖名稱,false 表示禁用佈局 |
| $params | array | 自訂模組參數(名稱=>值) |
__construct($id, $parent, $config)public function __construct($id, $parent = null, $config = []) {
$this->id = $id;
$this->module = $parent;
parent::__construct($config); // 呼叫 ServiceLocator::__construct 註冊組件
}
getInstance() / setInstance()public static function getInstance() {
$class = get_called_class();
return isset(Yii::$app->loadedModules[$class]) ? Yii::$app->loadedModules[$class] : null;
}
public static function setInstance($instance) {
if ($instance === null) unset(Yii::$app->loadedModules[get_called_class()]);
else Yii::$app->loadedModules[get_class($instance)] = $instance;
}
提供靜態存取當前請求中的模組實例,支援單一請求多模組共存。
init()public function init() {
if ($this->controllerNamespace === null) {
$class = get_class($this);
if (($pos = strrpos($class, '\\')) !== false) {
$this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
}
}
}
若未手動設定 controllerNamespace,自動推導為「當前類別命名空間\controllers」。
getUniqueId()public function getUniqueId() {
return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
}
遞歸拼接父模組 ID,形成 admin/user/profile 等層級路徑。
getBasePath() / setBasePath()public function getBasePath() {
if ($this->_basePath === null) {
$ref = new \ReflectionClass($this);
$this->_basePath = dirname($ref->getFileName());
}
return $this->_basePath;
}
public function setBasePath($path) {
$path = Yii::getAlias($path);
$real = realpath($path);
if ($real && is_dir($real)) $this->_basePath = $real;
else throw new InvalidParamException("目錄不存在: $path");
}
利用 Reflection 取得類別檔案所在目錄作為預設基礎路徑,支援別名與實體路徑驗證。
getViewPath():預設 basePath/viewsgetLayoutPath():預設 viewPath/layoutsconst EVENT_BEFORE_ACTION = 'beforeAction'; const EVENT_AFTER_ACTION = 'afterAction';
控制器執行動作前後觸發,可透過 ActionEvent::isValid 中斷執行。
Module 類別封裝了模組化應用的所有核心邏輯:命名空間慣例、路由解析、視圖查找、子模組樹管理、組件註冊(繼承 ServiceLocator)。理解其原始碼有助於深度客製化 Yii2 應用架構。