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

Yii2 源碼解讀:Module 類別核心架構與屬性詳解

     編輯:PHP 相關知識

Yii2 源碼解讀:Module 類別核心架構與屬性詳解

yii\base\Module 是所有模組與應用程式(Application)的基類,定義了模組的生命週期、屬性配置、子模組管理、控制器對應、視圖路徑解析等核心功能。本文節選關鍵原始碼並加註解析。

核心屬性

屬性型別說明
$idstring模組唯一 ID,用於區分同父模組下的子模組
$moduleModule|null父模組實例,頂層為 null
$controllerNamespacestring控制器類別命名空間,預設為 模組命名空間\controllers
$controllerMaparray控制器 ID 到類別配置的映射,支援字串或陣列配置
$defaultRoutestring預設路由,預設 default(對應 DefaultController::actionIndex)
$layoutstring|bool佈局視圖名稱,false 表示禁用佈局
$paramsarray自訂模組參數(名稱=>值)

關鍵方法解析

1. 建構子 __construct($id, $parent, $config)

public function __construct($id, $parent = null, $config = []) {
    $this->id = $id;
    $this->module = $parent;
    parent::__construct($config); // 呼叫 ServiceLocator::__construct 註冊組件
}

2. 實例存取 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;
}

提供靜態存取當前請求中的模組實例,支援單一請求多模組共存。

3. 初始化 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」。

4. 唯一 ID getUniqueId()

public function getUniqueId() {
    return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
}

遞歸拼接父模組 ID,形成 admin/user/profile 等層級路徑。

5. 基礎路徑 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 取得類別檔案所在目錄作為預設基礎路徑,支援別名與實體路徑驗證。

6. 視圖/佈局路徑

  • getViewPath():預設 basePath/views
  • getLayoutPath():預設 viewPath/layouts

事件機制

const EVENT_BEFORE_ACTION = 'beforeAction';
const EVENT_AFTER_ACTION  = 'afterAction';

控制器執行動作前後觸發,可透過 ActionEvent::isValid 中斷執行。

總結

Module 類別封裝了模組化應用的所有核心邏輯:命名空間慣例、路由解析、視圖查找、子模組樹管理、組件註冊(繼承 ServiceLocator)。理解其原始碼有助於深度客製化 Yii2 應用架構。

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