在 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 等)及進階路由配置,包括路由分組、中介層與參數擷取。
- **中介層支援:**Slim 的中介層能允許您在進入應用邏輯前或回應送回客戶端前執行任務,如驗證、記錄、CORS 處理等。
Slim 十分適合建立 RESTful API、快速原型,及針對獨立功能的專案開發。
在 ServBay 建立並運行 Slim 專案
本教學將利用 ServBay 預設的 PHP 環境及網站功能,快速完成 Web 伺服器設定,讓您的 Slim 專案順利運作。
事前準備
開始前,請確認已完成以下步驟:
- **安裝並啟動 ServBay:**請確保您已在 macOS 或 Windows 系統上安裝 ServBay,且已啟動 ServBay 應用程式。
- **ServBay 內建 Composer:**ServBay 預設整合 Composer,無需額外安裝。
建立 Slim 專案
ServBay 建議開發者將所有網站專案統一存放在下列目錄中,方便 ServBay 管理與設定:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
進入 ServBay 網站根目錄:
macOS:
bashcd /Applications/ServBay/www
1Windows:
cmdcd C:\ServBay\www
1**建立專案目錄:**新增目錄來存放 Slim 專案。
bashmkdir servbay-slim-app
1進入專案目錄:
bashcd servbay-slim-app
1**透過 Composer 安裝 Slim:**在專案目錄下使用 Composer 安裝 Slim 及其 PSR-7 實現。
bashcomposer require slim/slim "^4.0" slim/psr7 -W
1此指令會下載 Slim 框架和
slim/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
目錄:- macOS:
/Applications/ServBay/www/servbay-slim-app/public
- Windows:
C:\ServBay\www\servbay-slim-app\public
因為 Slim 的入口檔
index.php
位於public
資料夾中,Web 伺服器需指向此目錄。- macOS:
- 儲存網站設定。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)。
- 使用管理工具(如 MySQL/MariaDB 的 phpMyAdmin,PostgreSQL 的 pgAdmin)或命令列,建立新資料庫,例如命名為
servbay_slim_app
。 - ServBay 預設 root 密碼通常為
password
,可在介面查詢或修改。
- **安裝並設定 Phinx(資料庫遷移工具):**Phinx 是流行的 PHP 資料庫遷移工具,可管理資料結構版本化。
- 在專案根目錄安裝 Phinx:
- macOS:
/Applications/ServBay/www/servbay-slim-app
- Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require robmorgan/phinx
1 - macOS:
- 初始化 Phinx 設定:bash這會於根目錄建立
vendor/bin/phinx init
1phinx.yml
設定檔,請編輯內容設定資料庫連線,例如:yamlpaths: 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 在專案根目錄安裝 Phinx:
- **建立遷移檔案:**用 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:**於專案根目錄安裝:
- macOS:
/Applications/ServBay/www/servbay-slim-app
- Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require illuminate/database
1- macOS:
**於
public/index.php
初始化資料庫連線:**在require __DIR__ . '/../vendor/autoload.php';
後、$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();
前新增下列路由:
php
// ... 前面初始化程式碼與 '/' 路由 ...
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', // 用 time() 保證信箱唯一
'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();
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
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 範例
假設已啟動 PostgreSQL 套件、建立 servbay_slim_app
資料庫,並執行 Phinx 遷移建立 users
表(確保 Phinx 設定 adapter/port 分別為 pgsql
/5432
)。
修改 public/index.php
的資料庫連線設定,將 driver
改成 pgsql
並加入 schema
:
php
$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
]);
// ... 其他 Eloquent 初始化不變 ...
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
於 public/index.php
、$app->run();
前新增下列路由:
php
// ... 前面初始化程式碼及 '/' 路由 ...
// ... 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', // 用 time() 保證信箱唯一
'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();
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
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
,取得所有用戶並以 JSON 顯示。
Memcached 範例
ServBay 內建 Memcached 套件及 PHP 的 ext-memcached
擴充。只需額外安裝 PHP 客戶端庫。以 memcached/memcached
為例:
**安裝 Memcached 客戶端:**於專案根目錄安裝:
- macOS:
/Applications/ServBay/www/servbay-slim-app
- Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require memcached/memcached
1- macOS:
**於
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
擴充。只需安裝 PHP 客戶端庫。以下示範 predis/predis
:
**安裝 Redis 客戶端庫:**於專案根目錄安裝:
- macOS:
/Applications/ServBay/www/servbay-slim-app
- Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require predis/predis
1- macOS:
**於
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
40
**存取方式:**前往 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 應用創作!