在 ServBay 中建立並執行 Zend Framework (Laminas) 專案
概述
Zend Framework(現為 Laminas Project 的一部分)是一個功能強大的開源 PHP 框架,提供了一系列高品質、以物件導向為核心的元件,適合開發現代 Web 應用及服務。它以靈活性、模組化設計及高效能著稱,是從簡單網站到企業級複雜應用的理想選擇。
ServBay 是專為 macOS 設計的本地 Web 開發環境,整合了 PHP、多種 Web 伺服器(如 Caddy、Nginx)、多種資料庫(如 MySQL、PostgreSQL、MongoDB)、快取服務(如 Redis、Memcached)以及其他開發工具。ServBay 為這些套件的安裝、管理與設定帶來極大便利,讓你能輕鬆在本地執行各種 PHP 框架專案。
本文件將引導你如何在 ServBay 環境下建立並執行一個 Zend Framework (Laminas) 專案,並示範如何整合 ServBay 所支援的資料庫及快取服務。
前置條件
開始前,請先完成以下準備:
- 安裝 ServBay: 你已經在 macOS 上成功安裝並啟動了 ServBay。如果尚未安裝,請造訪 ServBay 官方網站 取得下載與安裝說明。
- 確保所需軟體包: 請確認 ServBay 已安裝並啟動下列必要組件,包括:
- 至少一個 PHP 版本(建議使用 PHP 8.x 或更高,因為新版 Zend Framework / Laminas 通常需要較新 PHP)。
- Web 伺服器(Caddy 或 Nginx)。
- Composer(ServBay 通常預裝)。
- 你打算使用的資料庫服務(如 MySQL、PostgreSQL)和快取服務(如 Memcached、Redis)。可於 ServBay 控制面板輕鬆啟動這些服務。
建立 Zend Framework 專案
ServBay 建議你將網站專案統一存放於 /Applications/ServBay/www
目錄下,方便 ServBay 自動管理和設定專案。
進入網站根目錄
開啟終端機,切換到 ServBay 建議的網站根目錄:
bashcd /Applications/ServBay/www
1用 Composer 建立專案
ServBay 出廠預裝 Composer,無需額外安裝。執行 Composer 的
create-project
指令,建立新的 Zend Framework (Laminas skeleton application) 專案,例如建立於servbay-zend-app
資料夾:bashcomposer create-project laminas/laminas-skeleton-application servbay-zend-app
1執行後將會把 Zend Framework (Laminas) 的骨架程式安裝於
servbay-zend-app
目錄並下載所需依賴。進入專案目錄
移動至剛剛建立的專案目錄:
bashcd servbay-zend-app
1
設定 Web 伺服器
為了能通過瀏覽器存取你的 Zend Framework 專案,需在 ServBay 內新增一個網站設定。
- 開啟 ServBay 控制面板: 啟動 ServBay 應用程式。
- 前往網站設定: 在 ServBay 控制台找到並點選 網站 (Websites) 分頁。
- 新增網站: 點選左下角的
+
以新增一組網站設定。 - 填寫網站資訊:
- 名稱 (Name): 為你的網站命名,例如
My Zend Dev Site
。 - 網域 (Domain): 輸入你想用於瀏覽器存取該專案的網域。為避免與真實網域衝突,建議用
.local
或.test
結尾,例如servbay-zend-test.local
。ServBay 會自動設定本地 DNS 解析。 - 網站類型 (Website Type): 選擇
PHP
。 - PHP 版本 (PHP Version): 選擇網站執行所需的 PHP 版本(如
8.3
),並確認此版本已存在且運作正常。 - 網站根目錄 (Document Root): 這是 Web 伺服器對外服務的目錄。Zend Framework 的進入點
index.php
位於專案的public
文件夾下,因此根目錄請指定為/Applications/ServBay/www/servbay-zend-app/public
。
- 名稱 (Name): 為你的網站命名,例如
- 儲存並重啟: 點選 保存 (Save)。ServBay 會出現套用變更提示,確認後 Web 伺服器會自動重載設定,新網站即生效。
詳盡網站設定步驟請參閱 ServBay 文件內 新增第一個網站 章節。
基本 "Hello ServBay!" 範例
現在我們將修改專案程式,讓存取根目錄網址(/
)時能顯示 "Hello ServBay!"。
設定路由與控制器 (module.config.php)
編輯專案根目錄下的
module/Application/config/module.config.php
。確保檔案中包含以下基本路由與控制器設定:php<?php declare(strict_types=1); namespace Application; use Laminas\Router\Http\Literal; use Laminas\Router\Http\Segment; use Laminas\ServiceManager\Factory\InvokableFactory; return [ 'router' => [ 'routes' => [ 'home' => [ 'type' => Literal::class, 'options' => [ 'route' => '/', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'index', ], ], ], // ... 其他路由設定 ], ], 'controllers' => [ 'factories' => [ Controller\IndexController::class => InvokableFactory::class, ], ], 'view_manager' => [ 'display_not_found_reason' => true, 'display_exceptions' => true, 'doctype' => 'HTML5', 'not_found_template' => 'error/404', 'exception_template' => 'error/index', 'template_map' => [ 'layout/layout' => __DIR__ . '/../view/layout/layout.phtml', 'application/index/index' => __DIR__ . '/../view/application/index/index.phtml', 'error/404' => __DIR__ . '/../view/error/404.phtml', 'error/index' => __DIR__ . '/../view/error/index.phtml', ], 'template_path_stack' => [ __DIR__ . '/../view', ], ], // ... 其他設定 ];
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注意: 上述僅為
module.config.php
中的相關片段,請將其彙整入現有設定陣列中。確保有'home'
路由與Controller\IndexController::class
工廠定義。建立或編輯控制器 (IndexController.php)
編輯(或新增)檔案
module/Application/src/Controller/IndexController.php
,確保indexAction
方法會傳送訊息給視圖:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; class IndexController extends AbstractActionController { /** * 預設 action,顯示歡迎頁。 */ public function indexAction() { // 回傳 ViewModel,並將 'message' 變數傳給視圖 return new ViewModel([ 'message' => 'Hello ServBay!', ]); } // ... 其他 action 方法 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24建立或編輯視圖檔 (index.phtml)
編輯或新增
module/Application/view/application/index/index.phtml
,以顯示控制器傳來的message
變數:php<h1><?php echo $this->message; ?></h1>
1這利用 Zend Framework (Laminas) 視圖輔助變數
$this->message
存取控制器所傳入的資料。
存取網站
開啟你的瀏覽器,前往 ServBay 所設定的網域,例如 https://servbay-zend-test.local
。
若一切配置正確,你將會看見頁面顯示 Hello ServBay!
——這代表專案已成功運作於 ServBay 環境下。
資料庫與快取整合範例
ServBay 提供多種資料庫與快取服務。以下將示範如何在 Zend Framework 專案內連接與操作 Memcached、Redis、MySQL 及 PostgreSQL。
重要提醒: 以下各資料庫及快取示範皆為獨立展示。實際開發時,通常會依需求選擇一種資料庫與一種或多種快取服務,並利用依賴注入等方式來管理連線。執行這些範例時,請事先在 ServBay 啟動對應的 MySQL、PostgreSQL、Memcached、Redis 等服務。
資料庫操作範例 - 建立資料表
首先,我們示範如何使用 Laminas DB 元件與資料庫互動,包括手動建立一個簡單的資料表。以下為建立資料表的范例程式碼,而非完整使用 Laminas Migrations 工具。
安裝 Laminas DB 元件
於專案根目錄下使用 Composer 安裝 Laminas DB 組件:
bashcomposer require laminas/laminas-db
1手動建立資料庫
執行資料庫操作前,請先於 ServBay 的資料庫管理工具(如 phpMyAdmin、pgAdmin、MongoDB Compass 等)建立名為
servbay_zend_app
的資料庫。ServBay MySQL/MariaDB 的預設帳號:root
,密碼:password
;PostgreSQL 預設帳號同為root
,密碼同樣是password
。定義並執行建表 SQL 腳本 (範例)
新增 PHP 檔(如
create_users_table.php
,可置於專案根目錄或暫存目錄),內容如下:php<?php // create_users_table.php use Laminas\Db\Adapter\Adapter; use Laminas\Db\Sql\Sql; // 假設你使用 MySQL 或 MariaDB $adapter = new Adapter([ 'driver' => 'Pdo_Mysql', // 或 'Pdo_Pgsql' 'database' => 'servbay_zend_app', 'username' => 'root', 'password' => 'password', // ServBay 預設密碼 'hostname' => '127.0.0.1', // 'port' => 3306, // MySQL 預設埠 // 'port' => 5432, // PostgreSQL 預設埠 ]); $sql = new Sql($adapter); // 定義建立 users 資料表的 SQL $create = $sql->createTable('users') ->addColumn(new \Laminas\Db\Sql\Ddl\Column\Integer('id', false, null, ['AUTO_INCREMENT' => true])) ->addColumn(new \Laminas\Db\Sql\Ddl\Column\Varchar('name', 255)) ->addColumn(new \Laminas\Db\Sql\Ddl\Column\Varchar('email', 255, ['UNIQUE' => true])) ->addConstraint(new \Laminas\Db\Sql\Ddl\Constraint\PrimaryKey('id')); echo "Executing SQL:\n"; echo $sql->buildSqlString($create, $adapter->getPlatform()) . "\n"; try { // 執行 SQL $adapter->query( $sql->buildSqlString($create, $adapter->getPlatform()), Adapter::QUERY_MODE_EXECUTE ); echo "Table 'users' created successfully.\n"; } catch (\Exception $e) { echo "Error creating table: " . $e->getMessage() . "\n"; }
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注意: 這僅為手動執行之範例。實際專案建議使用 Laminas Migrations 來維護資料庫結構。
可於終端機以 PHP CLI 執行此腳本(確定在專案目錄下或知曉正確路徑):
bashphp create_users_table.php
1
MySQL 整合範例
說明如何在 Zend Framework 控制器內連接並查詢 MySQL 資料庫。
設定資料庫連線
編輯
config/autoload/global.php
,設定 MySQL 連線資訊。若該檔案已有db
設定則修改,否則請加入:php<?php // config/autoload/global.php return [ 'db' => [ 'driver' => 'Pdo_Mysql', 'database' => 'servbay_zend_app', // 請確定該資料庫存在 'username' => 'root', // ServBay 預設帳號 'password' => 'password', // ServBay 預設密碼 'hostname' => '127.0.0.1', 'port' => 3306, 'charset' => 'utf8mb4', ], // ... 其他全域設定 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14設定控制器工廠 (module.config.php)
為讓控制器可注入
Laminas\Db\Adapter\Adapter
,需為IndexController
設定工廠。於module/Application/config/module.config.php
的controllers
段落將InvokableFactory
改為下列工廠:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\ServiceManager\Factory\InvokableFactory; use Laminas\Db\Adapter\AdapterInterface; return [ // ... 其他設定 'controllers' => [ 'factories' => [ Controller\IndexController::class => function($container) { // 從 Service Manager 取得資料庫適配器 $adapter = $container->get(AdapterInterface::class); // 建立 IndexController 實例並注入適配器 return new Controller\IndexController($adapter); }, ], ], 'service_manager' => [ 'aliases' => [ // 將 AdapterInterface 指向實體 Adapter AdapterInterface::class => 'Laminas\Db\Adapter\Adapter', ], 'factories' => [ // 定義 Laminas\Db\Adapter\Adapter 工廠 'Laminas\Db\Adapter\Adapter' => \Laminas\Db\Adapter\AdapterServiceFactory::class, ], ], // ... 其他設定 ];
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注意: 請將工廠設定合併進原有設定,特別要完整保留
service_manager
的aliases
與factories
。設定路由 (module.config.php)
在
module/Application/config/module.config.php
內為 MySQL 範例新增路由:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... 既有路由 'mysql-add' => [ 'type' => Literal::class, 'options' => [ 'route' => '/mysql-add', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'mysqlAdd', ], ], ], 'mysql' => [ 'type' => Literal::class, 'options' => [ 'route' => '/mysql', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'mysql', ], ], ], ], ], // ... 其他設定 ];
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請將以上路由加入
router
的routes
下。新增控制器方法 (IndexController.php)
編輯
module/Application/src/Controller/IndexController.php
,加上建構子與mysqlAddAction
、mysqlAction
方法:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; use Laminas\Db\Adapter\AdapterInterface; use Laminas\Db\Sql\Sql; class IndexController extends AbstractActionController { private $adapter; // 建構子,注入資料庫適配器 public function __construct(AdapterInterface $adapter) { $this->adapter = $adapter; } /** * 預設 action,顯示歡迎頁。 */ public function indexAction() { return new ViewModel([ 'message' => 'Hello ServBay!', ]); } /** * 透過 MySQL 將用戶加入 'users' 資料表。 */ public function mysqlAddAction() { $sql = new Sql($this->adapter); $insert = $sql->insert('users') ->values([ 'name' => 'ServBay Demo User', 'email' => '[email protected]', // 範例信箱 ]); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); // 檢查插入結果,回傳訊息 $message = $result->getAffectedRows() > 0 ? 'MySQL User added successfully.' : 'Failed to add MySQL user.'; return new ViewModel([ 'message' => $message, ]); } /** * 透過 MySQL 查詢 'users' 資料表所有使用者。 */ public function mysqlAction() { $sql = new Sql($this->adapter); $select = $sql->select('users'); $statement = $sql->prepareStatementForSqlObject($select); $result = $statement->execute(); $users = []; foreach ($result as $row) { $users[] = $row; } // 將結果轉成 JSON 字串傳給視圖 return new ViewModel([ 'users' => json_encode($users, JSON_PRETTY_PRINT), ]); } // ... 其他 action 方法 }
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請將建構子及以上兩個方法加入
IndexController
類別中。建立視圖檔
建立
module/Application/view/application/index/mysql-add.phtml
:php<h1><?php echo $this->message; ?></h1>
1建立
module/Application/view/application/index/mysql.phtml
:php<h1>MySQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2存取 MySQL 範例
請確認 ServBay 的 MySQL 服務已啟動。 首先造訪
https://servbay-zend-test.local/mysql-add
以新增一位使用者,畫面會顯示 "MySQL User added successfully."。 再造訪https://servbay-zend-test.local/mysql
,將會看到已加入的使用者資料(JSON 格式)。
PostgreSQL 整合範例
示範如何在 Zend Framework 控制器內連接並查詢 PostgreSQL 資料庫。
設定資料庫連線
編輯
config/autoload/global.php
,指定 PostgreSQL 連線資訊。註: 若同時運行 MySQL 及 PostgreSQL 範例,請用不同設定檔或手動切換db
設定,此例假設切到 PostgreSQL:php<?php // config/autoload/global.php return [ 'db' => [ 'driver' => 'Pdo_Pgsql', 'database' => 'servbay_zend_app', 'username' => 'root', 'password' => 'password', 'hostname' => '127.0.0.1', 'port' => 5432, ], // ... 其他全域設定 ];
1
2
3
4
5
6
7
8
9
10
11
12
13設定控制器工廠 (module.config.php)
(與 MySQL 範例相同)請確保
module/Application/config/module.config.php
的controllers
及service_manager
配置妥當。若已依前述步驟設定,可跳過此步。設定路由 (module.config.php)
在
module/Application/config/module.config.php
中新增 PostgreSQL 路由:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... 既有路由 'pgsql-add' => [ 'type' => Literal::class, 'options' => [ 'route' => '/pgsql-add', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'pgsqlAdd', ], ], ], 'pgsql' => [ 'type' => Literal::class, 'options' => [ 'route' => '/pgsql', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'pgsql', ], ], ], ], ], // ... 其他設定 ];
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請將以上路由加入
router
的routes
下。新增控制器方法 (IndexController.php)
編輯
module/Application/src/Controller/IndexController.php
,加上pgsqlAddAction
與pgsqlAction
:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; use Laminas\Db\Adapter\AdapterInterface; use Laminas\Db\Sql\Sql; class IndexController extends AbstractActionController { private $adapter; public function __construct(AdapterInterface $adapter) { $this->adapter = $adapter; } // ... 既有 action(如 indexAction, mysqlAddAction, mysqlAction) /** * 透過 PostgreSQL 將用戶加入 'users' 資料表。 */ public function pgsqlAddAction() { $sql = new Sql($this->adapter); $insert = $sql->insert('users') ->values([ 'name' => 'ServBay Demo User', 'email' => '[email protected]', // 範例信箱 ]); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); // 檢查插入結果,回傳訊息 $message = $result->getAffectedRows() > 0 ? 'PostgreSQL User added successfully.' : 'Failed to add PostgreSQL user.'; return new ViewModel([ 'message' => $message, ]); } /** * 透過 PostgreSQL 查詢 'users' 資料表所有使用者。 */ public function pgsqlAction() { $sql = new Sql($this->adapter); $select = $sql->select('users'); $statement = $sql->prepareStatementForSqlObject($select); $result = $statement->execute(); $users = []; foreach ($result as $row) { $users[] = $row; } // 將結果轉成 JSON 給視圖 return new ViewModel([ 'users' => json_encode($users, JSON_PRETTY_PRINT), ]); } }
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請將兩方法加入
IndexController
。建立視圖檔
建立
module/Application/view/application/index/pgsql-add.phtml
:php<h1><?php echo $this->message; ?></h1>
1建立
module/Application/view/application/index/pgsql.phtml
:php<h1>PostgreSQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2存取 PostgreSQL 範例
確保 ServBay 的 PostgreSQL 服務已啟動。 先訪
https://servbay-zend-test.local/pgsql-add
可新增使用者,畫面會顯示 "PostgreSQL User added successfully."。 再訪https://servbay-zend-test.local/pgsql
將看到剛剛新增的列表(JSON)。
Memcached 整合範例
說明如何在 Zend Framework 控制器中利用 Memcached 進行快取。
安裝 Memcached 介面套件
編輯
composer.json
加入:json// composer.json { "require": { "laminas/laminas-skeleton-application": "^1.0", "laminas/laminas-cache-storage-adapter-memcached": "^2.0" } }
1
2
3
4
5
6
7然後執行:
bashcomposer update
1ServBay 已預裝 PHP
memcached
擴充,無需額外安裝。設定路由 (module.config.php)
編輯
module/Application/config/module.config.php
,於routes
增加:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... 其他路由 'memcached' => [ 'type' => Literal::class, 'options' => [ 'route' => '/memcached', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'memcached', ], ], ], ], ], // ... 其他設定 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24新增控制器方法 (IndexController.php)
編輯
module/Application/src/Controller/IndexController.php
,加入memcachedAction
:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; use Laminas\Cache\StorageFactory; use Laminas\Cache\Storage\StorageInterface; class IndexController extends AbstractActionController { // ... 建構子與其他 action /** * Memcached 快取操作展示。 */ public function memcachedAction() { // 建立 Memcached 快取實例(ServBay 預設於 127.0.0.1:11211) $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'memcached', 'options' => [ 'servers' => [ ['127.0.0.1', 11211], ], 'ttl' => 300, ], ], 'plugins' => [ 'serializer', 'exception_handler' => ['throw_exceptions' => false], ], ]); $cacheKey = 'my_memcached_data'; $cachedData = $cache->getItem($cacheKey, $success); if (!$success) { // 未命中快取 $cachedData = 'Hello Memcached! (Data from source, cached at ' . date('Y-m-d H:i:s') . ')'; $cache->setItem($cacheKey, $cachedData); $cachedData .= ' - CACHE MISS'; } else { // 快取命中 $cachedData .= ' - CACHE HIT'; } return new ViewModel([ 'message' => $cachedData, ]); } }
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建立視圖檔
建立
module/Application/view/application/index/memcached.phtml
:php<h1>Memcached Example</h1> <p><?php echo $this->message; ?></p>
1
2存取 Memcached 範例
確認 ServBay 的 Memcached 已啟動。 造訪
https://servbay-zend-test.local/memcached
,首次將看到 "CACHE MISS" 消息;快取期間(本例 300 秒)內重訪,會看到 "CACHE HIT",且時間不變,證明資料取自快取。
Redis 整合範例
展示如何在 Zend Framework 控制器內使用 Redis 進行資料快取或儲存。
安裝 Redis 介面套件
編輯
composer.json
並加入:json// composer.json { "require": { "laminas/laminas-skeleton-application": "^1.0", "laminas/laminas-cache-storage-adapter-redis": "^2.0", "ext-redis": "*" } }
1
2
3
4
5
6
7
8然後執行:
bashcomposer update
1ServBay 已預裝 PHP 的
redis
擴充,無需額外安裝。設定路由 (module.config.php)
編輯
module/Application/config/module.config.php
,於routes
新增如下:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... 其他路由 'redis' => [ 'type' => Literal::class, 'options' => [ 'route' => '/redis', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'redis', ], ], ], ], ], // ... 其他設定 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24新增控制器方法 (IndexController.php)
於
module/Application/src/Controller/IndexController.php
加入redisAction
:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; use Laminas\Cache\StorageFactory; use Laminas\Cache\Storage\StorageInterface; class IndexController extends AbstractActionController { // ... 建構子與其他 action /** * Redis 資料快取範例。 */ public function redisAction() { // 建立 Redis 快取實例(ServBay 預設 127.0.0.1:6379) $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'redis', 'options' => [ 'server' => [ 'host' => '127.0.0.1', 'port' => 6379, // 'database' => 0, // 'password' => null, ], 'ttl' => 300, ], ], 'plugins' => [ 'serializer', 'exception_handler' => ['throw_exceptions' => false], ], ]); $cacheKey = 'my_redis_data'; $cachedData = $cache->getItem($cacheKey, $success); if (!$success) { // 未命中快取 $cachedData = 'Hello Redis! (Data from source, cached at ' . date('Y-m-d H:i:s') . ')'; $cache->setItem($cacheKey, $cachedData); $cachedData .= ' - CACHE MISS'; } else { // 快取命中 $cachedData .= ' - CACHE HIT'; } return new ViewModel([ 'message' => $cachedData, ]); } }
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建立視圖檔
建立
module/Application/view/application/index/redis.phtml
:php<h1>Redis Example</h1> <p><?php echo $this->message; ?></p>
1
2存取 Redis 範例
請確認 ServBay 的 Redis 服務正常。 前往
https://servbay-zend-test.local/redis
。首次訪問會出現 "CACHE MISS";快取期間重訪則顯示 "CACHE HIT",且時間戳不會更新,即為取自快取。
總結
透過上述步驟,你已於 ServBay 本地開發環境下成功建立、設定並執行 Zend Framework (Laminas) 專案,並掌握利用 ServBay 網站 功能指向專案公開目錄、結合 MySQL、PostgreSQL 資料庫,以及 Memcached、Redis 快取服務等操作。
ServBay 極大簡化了本地開發環境的安裝管理,讓你更專注在程式設計與專案拓展。善用 ServBay 豐富的整合套件和彈性設定,你能輕鬆於本地模擬接近真實的生產環境,全面提升開發效率。