建立並運行 CodeIgniter 專案
什麼是 CodeIgniter?
CodeIgniter 是一款輕量且效能卓越的 PHP Web 應用框架。它遵循 Model-View-Controller (MVC) 設計模式,旨在協助開發者快速打造功能豐富的 Web 應用程式。CodeIgniter 以其簡潔原始結構、良好效能與容易上手等特色,成為許多 PHP 工程師的首選框架。
CodeIgniter 的主要特色與優勢
- 輕量核心: CodeIgniter 的核心系統極為精簡,僅包含執行所需的基本元件,載入速度極快。
- 卓越效能: 框架注重效率設計,能應對高併發請求,提供優異的應用表現。
- 易學易用: 提供清晰的文件和直覺的 API,大幅降低學習門檻,使開發新手也能迅速上手。
- 高度彈性: 可依專案需求自由整合第三方函式庫,便於功能擴充與自訂。
- 活躍社群支援: 擁有龐大且積極的開發者社群,資源與支援豐富。
CodeIgniter 適用於小型專案到大型企業級應用的各種開發場景,協助開發者高效打造高品質 Web 解決方案。
使用 ServBay 架設 CodeIgniter 開發環境
ServBay 是一套專為 macOS 設計的本地 Web 開發環境工具,整合了 PHP、資料庫(MySQL、PostgreSQL、MongoDB)、快取(Redis、Memcached)、Web 伺服器(Caddy、Nginx、Apache)等多元套件,並提供直觀操作的管理介面。利用 ServBay,您能輕鬆搭建與管理 CodeIgniter 專案所需的完整開發環境。
本文將引導您如何利用 ServBay 的 PHP 環境與網站功能來建立、設定並運行 CodeIgniter 專案,以及示範如何整合多種資料庫和快取服務。
前置條件
在開始之前,請確認您已完成下列準備:
- 已於 macOS 系統成功安裝並啟動 ServBay。
- 已在 ServBay 中啟用您計劃使用的 PHP 版本(如 PHP 8.3)。
- 已於 ServBay 啟用所需的資料庫與快取套件(如 MySQL、PostgreSQL、Redis、Memcached)。
建立 CodeIgniter 專案
ServBay 建議將您的網站專案統一存放於 /Applications/ServBay/www
目錄下,有助於更好地管理本機網站。
安裝 Composer
ServBay 已在安裝時內建 Composer,通常無需額外手動安裝。您可以直接於終端機中使用
composer
指令。切換至網站根目錄
開啟終端機,進入 ServBay 建議的網站根目錄:
bashcd /Applications/ServBay/www
1建立 CodeIgniter 專案
使用 Composer 建立新的 CodeIgniter 4 專案。我們將專案資料夾命名為
servbay-codeigniter-app
:bashcomposer create-project codeigniter4/appstarter servbay-codeigniter-app
1Composer 將自動下載 CodeIgniter 架構與相依程式至
servbay-codeigniter-app
目錄。進入專案目錄
進入新建立的 CodeIgniter 專案資料夾:
bashcd /Applications/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 設定範例:
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 預設連接埠
];
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
若採用 PostgreSQL,DBDriver
請設為 'Postgre'
,連接埠一般為 5432
,且字元集設定也要適度調整。
設定快取連線 (Memcached/Redis)
若計畫導入 Memcached 或 Redis 作為快取,請於 app/Config/Cache.php
進行相關設定。
請編輯 app/Config/Cache.php
,找到對應的設定區段。ServBay 的 Memcached 預設連接埠為 11211
,Redis 預設為 6379
且一般無須密碼。
Memcached 範例設定:
public $memcached = [
'host' => '127.0.0.1', // ServBay Memcached 通常監聽於 127.0.0.1
'port' => 11211, // Memcached 預設連接埠
'weight' => 1,
];
2
3
4
5
Redis 範例設定:
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,
];
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): 擇您所需版本,如
8.3
。 - 網站根目錄 (Document Root): 這是關鍵!CodeIgniter 的進入點(
index.php
)位於專案目錄下的public
子資料夾。請務必將網站根目錄設為/Applications/ServBay/www/servbay-codeigniter-app/public
。
- 名稱 (Name): 如
- 按下 新增 (Add) 保存設置。
- 若 ServBay 要您套用更動,請點擊確認。
詳細步驟請參閱 新增第一個網站。
加入範例程式碼
為測試專案運作與資料庫快取連線,請修改 CodeIgniter 預設的 Home
控制器,新增一些範例方法。
編輯 app/Controllers/Home.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();
}
}
}
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
控制器新增的範例方法可被 URL 存取,請於 CodeIgniter 路由設定檔新增對應規則。
編輯 app/Config/Routes.php
,找到 $routes
定義區塊,加入如下路由:
// ... 其他路由規則 ...
// Memcached 範例路由
$routes->get('/memcached', 'Home::memcached');
// Redis 範例路由
$routes->get('/redis', 'Home::redis');
// 資料庫範例路由
$routes->get('/add-user', 'Home::addUser');
$routes->get('/list-users', 'Home::listUsers');
// ... 其他路由規則 ...
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
資料表。
建立資料表結構(執行遷移)
於終端機切換至 CodeIgniter 專案目錄:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1建立遷移檔: 利用 CodeIgniter CLI 產生設定
users
表的遷移檔:bashphp spark make:migration create_users_table
1此指令會於
app/Database/Migrations
產生一個新 PHP 檔。編輯遷移檔: 開啟新生成的遷移檔(檔名類似
YYYY-MM-DD-HHMMSS_CreateUsersTable.php
),於up()
方法中定義users
表欄位與索引。請注意,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, // Email 欄設為唯一 ], '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註: 上述範例利用條件式語法動態選取正確的預設時間戳語法。實務上,您可根據專案需求妥善規劃遷移管理機制或區分不同資料庫遷移檔。
執行遷移: 於終端機輸入下列指令,建立
users
表:bashphp spark migrate
1若執行成功,終端機會顯示遷移完成訊息。您也可用 ServBay 的資料庫管理工具(如 Adminer)檢查
servbay_codeigniter_app
資料庫內是否已產生users
表。
測試資料庫範例
確認您已在 app/Config/Database.php
正確設定資料庫連線資訊,並已完成 users
表的遷移。
新增用戶: 造訪
https://servbay-codeigniter-test.local/add-user
每次開啟此網址都會新增一筆用戶資料至users
表。畫面會顯示如User added successfully: [email protected]
的訊息。列出用戶資料: 造訪
https://servbay-codeigniter-test.local/list-users
此頁將查詢users
表所有用戶並以 JSON 顯示,畫面可見用戶資訊陣列。
結語
經由上述步驟,您已於 macOS ServBay 環境下成功建立、設定與運行一套 CodeIgniter 專案。您學會了如何以 Composer 建立新專案、把 ServBay網站指向正確目錄、設定 CodeIgniter 的資料庫及快取連線,並運用基礎範例驗證兩者整合。ServBay 大幅簡化了本機環境部署與管理流程,讓您能更專注於 CodeIgniter 應用的開發。