建立並執行 CodeIgniter 專案
什麼是 CodeIgniter?
CodeIgniter 是一套輕量且高效的 PHP Web 應用開發框架。它遵循 Model-View-Controller (MVC) 設計模式,目的是協助開發者快速構建功能完整的 Web 應用程式。CodeIgniter 結構精簡、效能卓越、易於學習,是許多 PHP 開發者的首選框架之一。
CodeIgniter 的主要特色與優勢
- 核心輕量: 系統只有執行所需的基本組件,載入快速,資源消耗低。
- 高效能: 框架設計強調運算效能,能夠有效應付高併發需求,並帶來極佳表現。
- 容易上手: 文件清楚且 API 無障礙,學習門檻低,開發者快速入門。
- 高度彈性: 可依專案需求自由選用並整合第三方函式庫,功能擴充自如。
- 活躍社群支援: 擁有龐大且積極的開發者社群,資源豐富、問題回應迅速。
CodeIgniter 適合不同規模的開發專案,無論小型網站或大型企業系統,都能助開發者高效打造高品質 Web 解決方案。
使用 ServBay 建置 CodeIgniter 開發環境
ServBay 是專為 macOS 及 Windows 設計的本機 Web 開發環境利器,整合 PHP、資料庫(MySQL, PostgreSQL, MongoDB)、快取(Redis, Memcached)、Web 伺服器(Caddy, Nginx, Apache)等多款工具並提供簡易管理介面。有了 ServBay,您可輕鬆建置並管理 CodeIgniter 所需環境。
本文將指引您如何在 ServBay 的 PHP 環境及「網站」功能下建立、設定與執行一個 CodeIgniter 專案,並示範整合多款資料庫與快取服務。
前置條件
開始前,請確保已完成以下準備:
- 已於 macOS 或 Windows 安裝並啟用 ServBay。
- 已於 ServBay 啟用您要使用的 PHP 版本(如 PHP 8.3)。
- 已於 ServBay 啟用計劃使用的資料庫及快取「套件」(如 MySQL, PostgreSQL, Redis, Memcached)。
建立 CodeIgniter 專案
ServBay 建議將您的網站專案集中在以下目錄下,有助於本機網站統一管理:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
安裝 Composer
ServBay 安裝時已預載 Composer,一般無需額外安裝,可直接在終端機使用
composer
指令。進入網站根目錄
開啟終端機,進入 ServBay 推薦的網站根目錄:
macOS:
bashcd /Applications/ServBay/www
1Windows:
cmdcd C:\ServBay\www
1建立 CodeIgniter 專案
使用 Composer 建立新 CodeIgniter 4 專案,目錄命名為
servbay-codeigniter-app
:bashcomposer create-project codeigniter4/appstarter servbay-codeigniter-app
1Composer 會將 CodeIgniter 骨架專案與相關依賴安裝至
servbay-codeigniter-app
資料夾。進入專案目錄
進入新建立的 CodeIgniter 專案目錄:
macOS:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1Windows:
cmdcd C:\ServBay\www\servbay-codeigniter-app
1
初始化設定
設定資料庫連線
CodeIgniter 的資料庫設定位於 app/Config/Database.php
。使用資料庫前,請先配置連線資訊。
若需使用資料庫,請先透過 ServBay 內建的資料庫管理工具(如 Adminer 或 phpMyAdmin,於 ServBay 介面可直接存取),建立名為 servbay_codeigniter_app
的資料庫。
接著編輯 app/Config/Database.php
,在 $default
陣列依照您所啟用的資料庫類型(例如 MySQL 或 PostgreSQL)填寫相關連線資訊。ServBay 預設資料庫帳號密碼多為 root
/ password
。
下為 MySQL 範例設定:
php
public $default = [
'DSN' => '',
'hostname' => '127.0.0.1', // ServBay 資料庫一般監聽於 127.0.0.1
'username' => 'root', // ServBay 預設帳號
'password' => 'password', // ServBay 預設密碼
'database' => 'servbay_codeigniter_app', // 專案資料庫名稱
'DBDriver' => 'MySQLi', // 依資料庫類型而定,MySQL 用 MySQLi 或 Pdo
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306, // MySQL 預設埠號
];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
如使用 PostgreSQL,請將 DBDriver
設為 'Postgre'
,port
通常是 5432
,並視情況調整字元集相關設置。
設定快取連線 (Memcached/Redis)
如擬採用 Memcached 或 Redis 作為快取,請至 app/Config/Cache.php
設定。
編輯 app/Config/Cache.php
,尋找相應設定區段。ServBay 的 Memcached 預設使用埠 11211
,Redis 則為 6379
,且通常不需密碼。
下為 Memcached 設定範例:
php
public $memcached = [
'host' => '127.0.0.1', // ServBay Memcached 通常監聽於 127.0.0.1
'port' => 11211, // Memcached 預設埠號
'weight' => 1,
];
1
2
3
4
5
2
3
4
5
Redis 設定例子:
php
public string $handler = 'redis'; // 設定使用 redis 為預設快取處理器
public $default = [ // Redis 設定通常在 default 陣列中
'host' => '127.0.0.1', // ServBay Redis 通常監聽於 127.0.0.1
'password' => null, // ServBay Redis 預設無密碼
'port' => 6379, // Redis 預設埠號
'timeout' => 0,
'database' => 0,
];
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
請依您已啟用的快取「套件」調整設定。
設定 Web 伺服器(ServBay 網站功能)
利用 ServBay 的「網站」功能設定 Web 伺服器,將其指向您的 CodeIgniter 專案:
- 開啟 ServBay 應用程式介面。
- 進入 網站 (Websites) 分頁。
- 點擊左下方
+
新增網站。 - 填寫新網站資訊:
- 名稱 (Name): 輸入易識別名稱,如
My First CodeIgniter Dev Site
。 - 網域 (Domain): 設定本地存取網域,如
servbay-codeigniter-test.local
。ServBay 會自動將.local
指向本機。 - 網站類型 (Site Type): 選擇
PHP
。 - PHP 版本 (PHP Version): 選所需 PHP 版本,如
8.3
。 - 網站根目錄 (Document Root): 重要步驟!CodeIgniter 入口檔 (
index.php
) 位於專案目錄下的public
資料夾,根目錄須設為專案內的public
資料夾:/Applications/ServBay/www/servbay-codeigniter-app/public
。
- 名稱 (Name): 輸入易識別名稱,如
- 點選 新增 (Add) 儲存。
- 如系統提示需套用變更,請點確認。
詳細說明請參見 新增第一個網站。
加入範例程式碼
為驗證專案運作,以及測試資料庫和快取,請修改 CodeIgniter 預設的 Home
控制器,加入範例方法。
編輯 app/Controllers/Home.php
,內容如下:
php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\Database\Exceptions\DatabaseException; // 引入資料庫異常類
use CodeIgniter\Cache\Exceptions\CacheException; // 引入快取異常類
class Home extends Controller
{
/**
* 預設首頁方法
*/
public function index(): string
{
// 回傳簡單歡迎訊息
return '<h1>Hello ServBay and CodeIgniter!</h1><p>Your CodeIgniter project is running on ServBay.</p>';
}
/**
* Memcached 範例方法
*/
public function memcached(): string
{
try {
$cache = \Config\Services::cache();
// 嘗試寫入快取
$success = $cache->save('servbay_memcached_key', 'Hello Memcached from CodeIgniter!', 60); // 快取 60 秒
if (!$success) {
return 'Error: Failed to save data to Memcached. Check Memcached service and configuration.';
}
// 嘗試讀取快取
$value = $cache->get('servbay_memcached_key');
if ($value === null) {
return 'Error: Failed to get data from Memcached. Cache might have expired or service is down.';
}
return 'Memcached Test Success: ' . $value;
} catch (CacheException $e) {
// 捕捉快取相關錯誤
return 'Cache Error: ' . $e->getMessage() . '. Ensure Memcached service is running and configured correctly.';
} catch (\Exception $e) {
// 捕捉其他可能的錯誤
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Redis 範例方法
*/
public function redis(): string
{
try {
$cache = \Config\Services::cache();
// 嘗試寫入快取
$success = $cache->save('servbay_redis_key', 'Hello Redis from CodeIgniter!', 60); // 快取 60 秒
if (!$success) {
return 'Error: Failed to save data to Redis. Check Redis service and configuration.';
}
// 嘗試讀取快取
$value = $cache->get('servbay_redis_key');
if ($value === null) {
return 'Error: Failed to get data from Redis. Cache might have expired or service is down.';
}
return 'Redis Test Success: ' . $value;
} catch (CacheException $e) {
// 捕捉快取相關錯誤
return 'Cache Error: ' . $e->getMessage() . '. Ensure Redis service is running and configured correctly.';
} catch (\Exception $e) {
// 捕捉其他可能的錯誤
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* 新增使用者資料至資料庫 (MySQL/PostgreSQL)
*/
public function addUser(): string
{
try {
$db = \Config\Database::connect();
// 檢查 'users' 資料表是否存在 (防呆)
if (!$db->tableExists('users')) {
return 'Error: "users" table does not exist. Please run database migrations first.';
}
// 插入資料
$data = [
'name' => 'ServBay Demo User',
'email' => 'user_' . time() . '@servbay.demo', // 利用 time() 產生唯一 email
];
$db->table('users')->insert($data);
// 檢查插入成功 (可選,insert() 通常回傳 true)
// if ($db->affectedRows() > 0) {
return 'User added successfully: ' . $data['email'];
// } else {
// return 'Error: Failed to add user.';
// }
} catch (DatabaseException $e) {
// 捕捉資料庫相關錯誤
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// 捕捉其他可能的錯誤
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* 讀取資料庫使用者資料 (MySQL/PostgreSQL)
*/
public function listUsers(): string
{
try {
$db = \Config\Database::connect();
// 檢查 'users' 資料表是否存在
if (!$db->tableExists('users')) {
return 'Error: "users" table does not exist. Please run database migrations first.';
}
// 查詢全部使用者
$users = $db->table('users')->get()->getResult();
if (empty($users)) {
return 'No users found in the database.';
}
// 回傳 JSON 格式使用者列表
return json_encode($users);
} catch (DatabaseException $e) {
// 捕捉資料庫相關錯誤
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// 捕捉其他可能的錯誤
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
此控制器提供更清楚的錯誤訊息與基礎診斷便利。
設定路由
為讓新增的 Home
控制器方法可透過網址存取,需於 CodeIgniter 路由檔設定對應規則。
開啟 app/Config/Routes.php
,於 $routes
定義區塊中加入以下規則:
php
// ... 其他路由規則 ...
// Memcached 範例路由
$routes->get('/memcached', 'Home::memcached');
// Redis 範例路由
$routes->get('/redis', 'Home::redis');
// 資料庫範例路由
$routes->get('/add-user', 'Home::addUser');
$routes->get('/list-users', 'Home::listUsers');
// ... 其他路由規則 ...
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
請將以上新路由加入原 $routes
定義區,不要覆蓋既有內容。
存取網站
此時您的 CodeIgniter 專案已於 ServBay 上妥善設置並執行。打開瀏覽器,透過先前設定的網域進行訪問:
首頁存取:
https://servbay-codeigniter-test.local
應會看到顯示Hello ServBay and CodeIgniter!
之頁面,代表專案已於 ServBay Web 伺服器正常運作。Memcached 範例存取:
https://servbay-codeigniter-test.local/memcached
若 Memcached 服務及設定正確,將顯示形如Memcached Test Success: Hello Memcached from CodeIgniter!
之結果。Redis 範例存取:
https://servbay-codeigniter-test.local/redis
若 Redis 服務及設定正確,將顯示形如Redis Test Success: Hello Redis from CodeIgniter!
之結果。
資料庫操作範例 (MySQL/PostgreSQL)
使用資料庫前,請先透過 CodeIgniter 遷移指令建立 users
資料表。
建立資料庫結構(執行遷移)
於終端機進入專案目錄:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1建立遷移檔案: 使用 CodeIgniter CLI 工具新增 migration 檔案,定義
users
資料表:bashphp spark make:migration create_users_table
1系統將於
app/Database/Migrations
資料夾產生新 PHP 檔。編輯遷移檔案: 開啟新生成之遷移檔(如
YYYY-MM-DD-HHMMSS_CreateUsersTable.php
),編輯up()
方法構建資料表欄位與索引。注意 MySQL 與 PostgreSQL 自動時間戳語法略有不同(CURRENT_TIMESTAMP
vsNOW()
),可善用 CodeIgniter 的RawSql
處理。範例參考:php<?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; use CodeIgniter\Database\RawSql; // 記得引入 RawSql class CreateUsersTable extends Migration { public function up() { $this->forge->addField([ 'id' => [ 'type' => 'INT', 'constraint' => 5, 'unsigned' => true, 'auto_increment' => true, ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '100', ], 'email' => [ 'type' => 'VARCHAR', 'constraint' => '100', 'unique' => true, // 信箱唯一欄位 ], 'created_at' => [ 'type' => 'TIMESTAMP', // 根據資料庫平台動態選擇預設值語法 // MySQL: 'default' => new RawSql('CURRENT_TIMESTAMP'), // PostgreSQL: 'default' => new RawSql('NOW()'), 'default' => new RawSql($this->db->getPlatform() === 'MySQLi' ? 'CURRENT_TIMESTAMP' : 'NOW()'), ], 'updated_at' => [ 'type' => 'TIMESTAMP', // MySQL: 'default' => new RawSql('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), // PostgreSQL: 'default' => new RawSql('NOW()'), 'default' => new RawSql($this->db->getPlatform() === 'MySQLi' ? 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP' : 'NOW()'), ], ]); $this->forge->addKey('id', true); // 設定 id 主鍵 $this->forge->createTable('users'); // 建立 users 資料表 } public function down() { // 遷移回滾時移除 users 資料表 $this->forge->dropTable('users'); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51注意: 本例以簡易邏輯根據平台切換時間戳預設語法,實務專案可依需求加強 migration 策略或分資料庫維護不同檔案。
執行遷移: 終端機下列指令建立資料表:
bashphp spark migrate
1執行成功後,終端機會顯示遷移完成提示。可於 ServBay 的資料庫管理工具(如 Adminer)確認
servbay_codeigniter_app
已創建users
資料表。
存取資料庫範例
請確保已於 app/Config/Database.php
正確設定資料庫連線,並完成 migration 建立 users
資料表。
新增使用者: 訪問
https://servbay-codeigniter-test.local/add-user
每次造訪此網址即新增一筆 user 至users
資料表,網頁會顯示形如User added successfully: user_XXXXXXXXXX@servbay.demo
之訊息。列出所有使用者: 訪問
https://servbay-codeigniter-test.local/list-users
將查詢資料表中所有紀錄並輸出 JSON,應能看到包含用戶資料之 JSON 陣列。
小結
依照以上流程,您已於 macOS (或 Windows) 上藉助 ServBay 成功建立並設定好 CodeIgniter 專案。學會利用 Composer 建專案、配置 ServBay「網站」功能指向正確目錄、設定 CodeIgniter 資料庫及快取連線,並以範例程式驗證整合成果。ServBay 有效簡化本機環境部署,助您專注 Web 應用開發,減少繁瑣設置。