CodeIgniter (CI) 的 Loader 類別是框架的核心樞紐,負責載入 Library、Model、View、Helper、Config 等所有資源。本文透過原始碼逐層剖析其運作原理,幫助開發者理解框架底層運作。
class CI_Loader {
protected $_ci_ob_level; // 輸出緩衝層級
protected $_ci_view_paths = []; // View 搜尋路徑
protected $_ci_library_paths = []; // Library 搜尋路徑
protected $_ci_model_paths = []; // Model 搜尋路徑
protected $_ci_helper_paths = []; // Helper 搜尋路徑
protected $_ci_classes = []; // 已載入類別快取
protected $_ci_models = []; // 已載入 Model 快取
protected $_ci_helpers = []; // 已載入 Helper 快取
protected $_ci_cached_vars = []; // 視圖變數快取
protected $_ci_varmap = [ // 類別名稱映射
'unit_test' => 'unit',
'user_agent' => 'agent'
];
public function __construct() {
$this->_ci_ob_level = ob_get_level();
$this->_ci_library_paths = [APPPATH, BASEPATH];
$this->_ci_helper_paths = [APPPATH, BASEPATH];
$this->_ci_model_paths = [APPPATH];
$this->_ci_view_paths = [APPPATH . 'views/' => TRUE];
log_message('debug', "Loader Class Initialized");
}
}
application/libraries/ 下的擴充類別 (MY_ 前綴)system/libraries/ 核心類別_ci_init_class() 實例化並掛載到 CI 超級物件 $CI->library_nameadmin/user_model)$CI->model_name 並記錄於 _ci_modelspublic function view($view, $vars = [], $return = FALSE) {
return $this->_ci_load([
'_ci_view' => $view,
'_ci_vars' => $this->_ci_object_to_array($vars),
'_ci_return' => $return
]);
}
核心邏輯在 _ci_load():
cascade 機制)$this 指向 CIextract() 變為區域變數ob_start(),支援短標籤重寫_ci_return 決定回傳字串或直接輸出到 Output 類別ob_get_level() 判斷處理方式application/helpers/MY_*_helper.php(需對應核心檔存在)include_once 避免重複定義函式動態擴充/移除資源搜尋路徑,支援模組化開發(如 HMVC),自動同步更新 library、model、helper、config、view 五大路徑陣列。
讀取 config/autoload.php,依序載入 packages、config、helper、language、library(含 database)、model。
// application/core/MY_Loader.php
class MY_Loader extends CI_Loader {
public function __construct() {
parent::__construct();
// 將預設 views 改為專案根目錄下的 templates
$this->_ci_view_paths = [FCPATH . '/templates/' => TRUE];
}
}
test_model.php,類別需為 Test_model extends CI_Model$this->load->library('foo', null, 'custom_name')_ci_ob_level 邏輯深入理解 Loader 機制,不僅能排除疑難雜症,更能在擴充框架時得心應手。