CodeIgniter 3 (CI3) 是經典的單入口 MVC 框架,核心文件不足 2MB,啟動流程清晰,適合學習 PHP 框架設計。本文按執行順序拆解 14 個關鍵加載步驟,並剖析核心源碼邏輯。
require BASEPATH/core/CodeIgniter.php。load_class() 載入基類,執行請求生命週期。load_class, get_config, log_message 等)。mark(), elapsed_time())。pre_system, pre_controller, post_controller…)。config_item(), $this->config->load())。routes.php 將 URI 映射為 Controller@method。$_GET/$_POST 獲取。&get_instance(),掛載所有 Library/Model/Helper 為屬性。APPPATH/controllers/...php 實例化,調用 $method()。$this->load->model/library/view/helper/database() 統一加載器。ob_end_flush()。<?php // system/core/Common.php
function &load_class($class, $directory = 'libraries', $prefix = 'CI_') {
static $_classes = []; // 靜態緩存,確保單例
if (isset($_classes[$class])) return $_classes[$class];
$name = false;
// 先找應用目錄,再找系統目錄(應用可覆蓋核心)
foreach ([APPPATH, BASEPATH] as $path) {
$file = $path . $directory . '/' . $class . '.php';
if (file_exists($file)) {
$name = $prefix . $class;
if (!class_exists($name, false)) require $file;
break;
}
}
if ($name === false) {
show_error("Unable to locate the specified class: {$class}.php");
}
$_classes[$class] = new $name(); // 實例化並緩存
return $_classes[$class];
}
關鍵點:引用返回 & 確保單例;APPPATH 優先於 BASEPATH 實現核心類覆寫;class_exists(..., false) 避免觸發自動加載器。
<?php // system/core/Controller.php
class CI_Controller {
private static $instance;
public function __construct() {
self::$instance = &$this; // 全局單例引用
// 將所有已加載的類掛載為 $this->屬性
foreach (is_loaded() as $var => $class) {
$this->$var =& load_class($var);
}
$this->load =& load_class('Loader', 'core');
$this->load->initialize();
log_message('info', "Controller Class Initialized");
}
public static function &get_instance() {
return self::$instance;
}
}
這就是為什麼在任何 Model/Library/View 中都能用 $CI =& get_instance(); $CI->db->query(...) 訪問框架資源。
<?php // system/core/Router.php (簡化)
protected function _set_routing() {
$uri = $this->uri->uri_string();
if ($uri === '') { // 首頁
$this->set_class($this->default_controller);
$this->set_method('index');
return;
}
// 1. 檢查自定義路由 routes.php
if (isset($this->routes[$uri])) { ... }
// 2. 正則路由
foreach ($this->routes as $pattern => $map) { ... }
// 3. 默認映射:controller/method/params
$segments = $this->uri->segments;
$this->set_class($segments[0] ?? $this->default_controller);
$this->set_method($segments[1] ?? 'index');
}
$config['cache_query_string'] = FALSE,頁面緩存繞過 5-13 步驟。$config['enable_hooks'] = FALSE,減少 Hooks.php 開銷。autoload.php 僅加載必須的庫/助手,按需 $this->load->library()。CI3 官方已停止更新 (2021/10/31),新項目建議:
CI3 以「單入口、單例超級對象、鉤子擴展、配置驅動」為核心架構,代碼簡潔易讀。深入理解其啟動流程與 load_class 機制,有助於排查疑難雜症、編寫核心擴展、平滑遷移至現代框架。