所有 HTTP 請求導向唯一入口腳本 public/index.php(CI4)或 index.php(CI3)。Web 伺服器重寫規則(Nginx/Apache)將非實體檔案請求轉發給入口:
# Nginx
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# Apache .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
index.php 載入 autoload.php(Composer)與框架核心 CodeIgniter.php。CodeIgniter\CodeIgniter 實例,執行 run()。app/Config/Routes.php),決定控制器/方法/參數。initController() 注入 Request/Response/Logger 等服務。terminate 事件,結束生命週期。CI_Model,透過 `$this->load->model('User_model')` 載入,使用 `$this->db` 查詢建構器/Active Record。CodeIgniter\Model,內建 CRUD、驗證、時間戳自動管理、資料映射、軟刪除。<?php namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model {
protected $table = 'users';
protected $allowedFields = ['email', 'name', 'password_hash', 'is_active'];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $dateFormat = 'datetime';
public function findActiveByEmail(string $email): ?array {
return $this->where('email', $email)->where('is_active', 1)->first();
}
}
<!-- app/Views/layout/main.php -->
<html><head><title>= esc($title) ?></title></head><body>
= $this->renderSection('content') ?>
</body></html>
<!-- app/Views/welcome.php -->
= $this->extend('layout/main') ?>
= $this->section('content') ?>
<h1>Welcome, = esc($user['name']) ?>!</h1>
= $this->endSection() ?>
CI_Controller,方法對應 URI 片段(`controller/method/param1/param2`)。BaseController(再繼承 CodeIgniter\Controller),支援依賴注入、請求/回應物件、過濾器、資源路由(`$routes->resource('photos')` 自動對應 RESTful 方法)。<?php namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\HTTP\ResponseInterface;
class Users extends BaseController {
protected $users;
public function __construct() {
$this->users = model(UserModel::class); // 服務定位器快捷方式
}
public function index() {
$data['users'] = $this->users->where('is_active', 1)->findAll();
return view('users/index', $data);
}
public function show($id = null) {
$user = $this->users->find($id);
if (!$user) throw new \CodeIgniter\Exceptions\PageNotFoundException();
return view('users/show', ['user' => $user]);
}
public function create() {
return view('users/create');
}
public function store() {
$rules = ['email' => 'required|valid_email|is_unique[users.email]', 'name' => 'required'];
if (!$this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$this->users->save([
'email' => $this->request->getPost('email'),
'name' => $this->request->getPost('name'),
'password_hash' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
]);
return redirect()->to('/users')->with('success', 'User created');
}
}
CI3 預設 `controller/method/params`,CI4 強烈建議在 app/Config/Routes.php 顯式定義:
$routes->get('/', 'Home::index');
$routes->get('users/(:num)', 'Users::show/$1');
$routes->post('users', 'Users::store');
$routes->resource('api/articles', ['controller' => 'Api\Articles']);
$routes->group('admin', ['filter' => 'auth'], static function($routes) {
$routes->get('dashboard', 'Admin\Dashboard::index');
});
優點:解耦 URI 與類別結構、支援 HTTP 動詞限制、中介軟體掛載、反向路由生成 URL。
CI4 採用 Config\Services 註冊單例/共享實例,控制器建構子自動注入:
public function __construct(
private readonly UserModel $users,
private readonly \Config\Email $emailConfig
) {}
視圖單元也能注入服務:`= service('renderer')->render('partials/menu') ?>`。
CI4 內建資料庫遷移(`php spark migrate`)與種子(`php spark db:seed UserSeeder`),版本控管結構變更,團隊協作無縫。
CodeIgniter 以輕量、低耦合、文檔詳盡著稱。CI4 重寫核心,引入現代 PHP 特性(命名空間、型別提示、服務容器、PSR 相容),保留單一入口與 MVC 經典架構,同時提供靈活的路由、強大的模型、安全的視圖層,是中小型專案快速落地的優秀選擇。