在 ServBay 中建立並執行 Slim 專案
本文件將引導您如何在 ServBay 這個強大的本機 Web 開發環境下,快速建立、設定並運行以 PHP 為基礎的 Slim Framework 專案。ServBay 整合了 PHP、Web 伺服器(Caddy/Nginx/Apache)及多種資料庫套件,是進行 Slim 開發的理想平台。
什麼是 Slim?
Slim 是一款輕量級的 PHP 微框架,專為快速構建簡潔卻功能強大的 Web 應用程式及 API 而設計。它提供了核心的路由、請求與回應處理功能,非常適合需要快速開發佈署的專案,或作為構建更複雜應用的基礎。
Slim 的主要特性與優勢
- 輕量級: Slim 框架核心程式碼規模小、資源佔用低,啟動速度快,適合打造小型至中型應用或微服務。
- 彈性高: Slim 設計上可按需擴充,能輕鬆與任何第三方套件或函式庫(如模板引擎、ORM、認證等)整合,讓您自由選用最合適的工具。
- 易於上手: 憑藉簡潔的 API 與清晰文件,開發者能快速理解其核心概念並進行開發。
- 強大路由功能: 支援多種 HTTP 方法(GET, POST, PUT, DELETE 等)以及複雜路由配置,包括路由群組、中介層與參數捕捉。
- 中介層(Middleware)支援: Slim 的中介層機制讓您能在請求進入主程式邏輯前或回應發送前執行任務,如驗證、記錄、CORS 等。
Slim 特別適合用於構建 RESTful API、快速原型開發及處理特定、獨立功能。
使用 ServBay 建立並執行 Slim 專案
本指南將利用 ServBay 已預先配置的 PHP 環境與網站功能,快速設定 Web 伺服器,並使您的 Slim 專案可以輕鬆被訪問。
前置需求
開始之前,請確保完成以下事項:
- 安裝與啟動 ServBay: 請確認 ServBay 已成功安裝於您的 macOS 系統,且 ServBay 應用程式正在執行中。
- ServBay 內建 Composer: ServBay 預設已整合 Composer,無須另外安裝。
建立 Slim 專案
ServBay 建議將所有網站專案統一存放於 /Applications/ServBay/www
目錄下,便於專案的管理與組態。
- 切換到 ServBay 的網站根目錄:bash
cd /Applications/ServBay/www
1 - 建立專案目錄: 新建一個目錄來存放 Slim 專案。bash
mkdir servbay-slim-app
1 - 進入專案目錄:bash
cd servbay-slim-app
1 - 使用 Composer 安裝 Slim: 在專案目錄下通過 Composer 安裝 Slim 框架及其 PSR-7 實作。bash此指令會將 Slim 與
composer require slim/slim "^4.0" slim/psr7 -W
1slim/psr7
函式庫下載至專案的vendor
目錄,並產生composer.json
及composer.lock
檔案。
初始化 Slim 應用
- 建立入口檔案: Slim 專案通常使用單一入口檔(如
public/index.php
)處理所有請求。於專案根目錄建立public
子目錄並在其中新增index.php
檔案。bashmkdir public touch public/index.php
1
2 - 編輯入口檔: 開啟
public/index.php
,加入以下 Slim 基本程式碼:php這段程式碼建立一個最簡單的 Slim 應用,對根 URL (<?php // 載入 Composer 自動加載檔案 require __DIR__ . '/../vendor/autoload.php'; // 導入必要的 PSR-7 介面與 Slim 工廠類 use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; // 建立 Slim 應用實體 $app = AppFactory::create(); // 增加一個基礎路由:處理 GET 請求到根路徑 '/' $app->get('/', function (Request $request, Response $response, $args) { // 寫入內容至回應主體 $response->getBody()->write("Hello ServBay!"); // 回傳回應物件 return $response; }); // 執行 Slim 應用 $app->run();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22/
) GET 請求進行路由,回傳包含 "Hello ServBay!" 文字的回應。
設定 ServBay 網站
要讓瀏覽器能存取您的 Slim 專案,需在 ServBay 裡設定一個網站(舊版稱為「主機」)。
- 開啟 ServBay 應用程式介面。
- 進入網站 (Websites) 功能模組。
- 點擊新增網站。
- 依據專案資訊填寫設定:
- 名稱 (Name):
My First Slim Dev Site
(或您喜歡的名稱) - 網域 (Domain):
servbay-slim-test.local
(建議本機開發結尾用.local
或.test
) - 網站類型 (Website Type):
PHP
- PHP 版本 (PHP Version): 選擇您所需的版本,例如
8.3
。 - 網站根目錄 (Document Root): 點選瀏覽,選擇專案中
public
目錄,即/Applications/ServBay/www/servbay-slim-app/public
。因為 Slim 的入口檔index.php
位於public
,Web 伺服器應將請求導向該目錄。
- 名稱 (Name):
- 儲存網站設定。ServBay 會自動更新 Web 伺服器組態並使之生效。
更詳細網站設定步驟,請參考新增第一個網站。
存取您的 Slim 網站
設定完成後,於瀏覽器輸入您設置的網址 https://servbay-slim-test.local
。
若一切順利,頁面上會顯示 Hello ServBay!
。這代表您的 Slim 專案已順利透過 ServBay 的 Web 伺服器運作。
資料庫整合範例
Slim 框架本身不內建資料庫抽象層,但可靈活整合多種 PHP 資料庫套件。本例選用 Laravel 的 Eloquent ORM(illuminate/database
元件)示範如何連線 MySQL、PostgreSQL,並附上 Memcached 與 Redis 的整合範例。
前置需求:建立資料庫與執行遷移
在進行資料庫整合前,需先於 ServBay 建立對應的資料庫,並為應用建立必要的資料表結構。
- 建立資料庫:
- 開啟 ServBay 應用程式,進入您啟用的資料庫套件(如 MySQL 或 PostgreSQL)。
- 透過 ServBay 提供的管理工具(如 MySQL/MariaDB 用 phpMyAdmin,PostgreSQL 用 pgAdmin)或命令行工具,建立新資料庫,例如命名為
servbay_slim_app
。 - ServBay 預設的資料庫 root 密碼多為
password
,可至 ServBay 介面查看或修改。
- 安裝與設定 Phinx(資料庫遷移工具): Phinx 是主流 PHP 資料庫遷移工具,有助於資料表結構版本控管。 * 於專案根目錄
/Applications/ServBay/www/servbay-slim-app
安裝 Phinx:bashcomposer require robmorgan/phinx
1
* 初始化 Phinx 設定:
```bash
vendor/bin/phinx init
```
執行後,會於專案根目錄建立 `phinx.yml` 設定檔。編輯設定內容,例如:
```yaml
paths:
migrations: '%%PHINX_CONFIG_DIR%%/db/migrations'
seeds: '%%PHINX_CONFIG_DIR%%/db/seeds'
environments:
default_migration_table: phinxlog
default_environment: development # 或您的設定名稱
development: # 依資料庫型態設定
adapter: mysql # 或 pgsql
host: 127.0.0.1
name: servbay_slim_app # 您剛建立的資料庫名稱
user: root
pass: password # 您的資料庫密碼
port: 3306 # MySQL 預設,PostgreSQL 預設 5432
charset: utf8mb4 # 建議 MySQL
collation: utf8mb4_unicode_ci # 建議 MySQL
version_order: creation
```
- 建立遷移檔案: 使用 Phinx 指令建立新遷移檔。bash這會於
vendor/bin/phinx create CreateUsersTable
1db/migrations
新增 PHP 檔,請開啟,於change()
方法中定義users
資料表結構:php<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class CreateUsersTable extends AbstractMigration { /** * Change Method. * * Write your reversible migrations using this method. * * More information on writing migrations is available here: * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method * * Remember to call "create()" or "update()" and NOT "save()" when working * with the Table class. */ public function change(): void { $table = $this->table('users'); $table->addColumn('name', 'string') ->addColumn('email', 'string', ['unique' => true]) ->addTimestamps() // 新增 created_at、updated_at 欄位 ->create(); } }
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 - 執行遷移: 於專案根目錄執行 Phinx,產生
users
資料表。bash重要提醒: 在測試後續資料庫範例程式前,務必完成資料庫建立與遷移。vendor/bin/phinx migrate
1
使用 illuminate/database 元件
我們將採用 Laravel 的 illuminate/database
作為 ORM 與查詢構建器。
安裝 illuminate/database: 於
/Applications/ServBay/www/servbay-slim-app
安裝所需套件。bashcomposer require illuminate/database
1於
public/index.php
初始化資料庫連線: 在require __DIR__ . '/../vendor/autoload.php';
之後、建立 Slim 應用$app = AppFactory::create();
之前,加入資料庫連線設定。php// ... 其他 require 與 use 語句 ... use Illuminate\Database\Capsule\Manager as Capsule; // 導入 Capsule 管理器 // 初始化 Eloquent ORM $capsule = new Capsule; // 新增資料庫連線設定(請依所用資料庫調整 driver 與參數) $capsule->addConnection([ 'driver' => 'mysql', // 或 'pgsql' 'host' => '127.0.0.1', 'database' => 'servbay_slim_app', // 您的資料庫名稱 'username' => 'root', // 資料庫帳號 'password' => 'password', // 資料庫密碼 'charset' => 'utf8mb4', // 若為 MySQL 建議使用 'collation' => 'utf8mb4_unicode_ci', // MySQL 建議 'prefix' => '', // PostgreSQL 需設定 schema // 'schema' => 'public', ]); // 全域可用 $capsule->setAsGlobal(); // 啟動 Eloquent $capsule->bootEloquent(); // ... 設定 Slim 應用實例 ($app = AppFactory::create();) ...
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
MySQL 範例
確認您已於 ServBay 啟動 MySQL 套件、建立 servbay_slim_app
資料庫,並透過 Phinx 建立了 users
資料表。
在 public/index.php
於 $app->run();
之前加上下列路由:
// ... 前段初始化與 '/' 路由 ...
use Illuminate\Database\Capsule\Manager as Capsule; // 請確認已導入
// 新增用戶資料的路由
$app->get('/mysql-add-user', function (Request $request, Response $response, $args) {
try {
Capsule::table('users')->insert([
'name' => 'ServBay Demo User',
'email' => 'servbay-demo-' . time() . '@servbay.test', // 保證 email 唯一
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$response->getBody()->write('User added to MySQL');
} catch (\Exception $e) {
$response->getBody()->write('Error adding user: ' . $e->getMessage());
$response = $response->withStatus(500); // 回傳錯誤狀態碼
}
return $response;
});
// 讀取用戶資料的路由
$app->get('/mysql-get-users', function (Request $request, Response $response, $args) {
try {
$users = Capsule::table('users')->get();
$response->getBody()->write($users->toJson()); // 以 JSON 格式輸出
$response = $response->withHeader('Content-Type', 'application/json'); // 設定 Content-Type
} catch (\Exception $e) {
$response->getBody()->write('Error fetching users: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// ... $app->run();
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
使用方式:
- 前往
https://servbay-slim-test.local/mysql-add-user
會在users
表中新增一筆新使用者。 - 前往
https://servbay-slim-test.local/mysql-get-users
會讀取所有使用者並以 JSON 回傳。
PostgreSQL 範例
假設您已於 ServBay 啟動 PostgreSQL 套件、成功建立 servbay_slim_app
資料庫,並經 Phinx 建立了 users
表(確保 Phinx 設定的 adapter
與 port
為 pgsql
與 5432
)。
請將 public/index.php
的資料庫連線設定 driver
改為 pgsql
並加入 schema
:
$capsule->addConnection([
'driver' => 'pgsql', // 修改為 pgsql
'host' => '127.0.0.1',
'database' => 'servbay_slim_app',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8', // PostgreSQL 多使用 utf8
'prefix' => '',
'schema' => 'public', // PostgreSQL 需加上 schema
]);
// ... 其餘初始化不變 ...
2
3
4
5
6
7
8
9
10
11
在 public/index.php
於 $app->run();
之前加上下列路由:
// ... 初始化程式與 '/' 路由 ...
// ... 若需,保留 MySQL 路由 ...
use Illuminate\Database\Capsule\Manager as Capsule; // 確保已載入
// 新增用戶的路由
$app->get('/pgsql-add-user', function (Request $request, Response $response, $args) {
try {
Capsule::table('users')->insert([
'name' => 'ServBay PG Demo User',
'email' => 'servbay-pg-demo-' . time() . '@servbay.test', // 保證 email 唯一
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$response->getBody()->write('User added to PostgreSQL');
} catch (\Exception $e) {
$response->getBody()->write('Error adding user: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// 讀取用戶資料的路由
$app->get('/pgsql-get-users', function (Request $request, Response $response, $args) {
try {
$users = Capsule::table('users')->get();
$response->getBody()->write($users->toJson());
$response = $response->withHeader('Content-Type', 'application/json');
} catch (\Exception $e) {
$response->getBody()->write('Error fetching users: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// ... $app->run();
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
使用方式:
- 前往
https://servbay-slim-test.local/pgsql-add-user
會為 PostgreSQL 的users
新增一筆資料。 - 前往
https://servbay-slim-test.local/pgsql-get-users
會查詢所有users
並以 JSON 回傳。
Memcached 範例
ServBay 內含 Memcached 套件及 PHP ext-memcached
擴展。僅需安裝客戶端即可操作,這裡使用 memcached/memcached
。
安裝 Memcached 客戶端套件: 於
/Applications/ServBay/www/servbay-slim-app
安裝:bashcomposer require memcached/memcached
1於
public/index.php
新增 Memcached 路由: 在$app->run();
之前加上下列路由:php// ... 其他初始化與資料庫路由 ... // 使用 Memcached 的路由 $app->get('/memcached-example', function (Request $request, Response $response, $args) { // 建立 Memcached 客戶端實例 $memcached = new Memcached(); // 加入 Memcached 伺服器 (ServBay 預設運行於 127.0.0.1:11211) $memcached->addServer('127.0.0.1', 11211); $cacheKey = 'my_servbay_cache_key'; // 嘗試從快取取得資料 $cachedData = $memcached->get($cacheKey); if ($cachedData === false) { // 若無快取,產生資料並寫入快取 $cachedData = 'Hello Memcached from ServBay! This was not cached.'; // 儲存資料進快取,ttl 設定為 60 秒 $memcached->set($cacheKey, $cachedData, 60); $response->getBody()->write($cachedData); } else { // 有快取則直接回傳 $response->getBody()->write('Hello Memcached from ServBay! This was served from cache.'); } return $response; }); // ... $app->run();
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
使用方式: 首次前往 https://servbay-slim-test.local/memcached-example
會顯示 "This was not cached.",之後(快取有效期間)則會顯示 "This was served from cache."。
Redis 範例
ServBay 內建 Redis 套件與 PHP ext-redis
擴展。僅需安裝客戶端即可操作,本例採 predis/predis
。
安裝 Redis 客戶端套件: 於
/Applications/ServBay/www/servbay-slim-app
安裝:bashcomposer require predis/predis
1於
public/index.php
新增 Redis 路由: 在$app->run();
之前加上下列路由:php// ... 前段初始化、資料庫與 Memcached 路由 ... use Predis\Client as RedisClient; // 導入 Predis 客戶端 // 使用 Redis 的路由 $app->get('/redis-example', function (Request $request, Response $response, $args) { try { // 建立 Redis 客戶端(ServBay 預設在 127.0.0.1:6379) $redis = new RedisClient([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); $cacheKey = 'my_servbay_redis_cache_key'; // 嘗試從快取取得資料 $cachedData = $redis->get($cacheKey); if ($cachedData === null) { // 若無快取,生成資料並寫入快取 $cachedData = 'Hello Redis from ServBay! This was not cached.'; // 寫入快取,60 秒過期 $redis->setex($cacheKey, 60, $cachedData); // SETEX key seconds value $response->getBody()->write($cachedData); } else { // 若有快取直接使用 $response->getBody()->write('Hello Redis from ServBay! This was served from cache.'); } } catch (\Exception $e) { // 捕捉連線或操作異常 $response->getBody()->write('Error connecting to Redis or performing operation: ' . $e->getMessage()); $response = $response->withStatus(500); } return $response; }); // ... $app->run();
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
使用方式: 首度造訪 https://servbay-slim-test.local/redis-example
將顯示 "This was not cached.",後續(快取有效期間)會顯示 "This was served from cache."。
總結
按照以上步驟,您已在 ServBay 本機開發環境順利建立 Slim Framework 專案並配置 ServBay 的網站功能,順利託管與訪問該專案。您也學會如何善用 ServBay 的多項套件(如 MySQL、PostgreSQL、Memcached、Redis)與 PHP 擴展,將資料庫與快取整合至您的 Slim 應用。ServBay 大幅簡化本機環境建置與管理流程,讓您能更專注在 Slim 應用開發本身。