Tạo và vận hành dự án Zend Framework (Laminas) trên ServBay
Tổng quan
Zend Framework (hiện là một phần của dự án Laminas) là framework PHP mã nguồn mở mạnh mẽ, cung cấp nhiều thành phần hướng đối tượng chất lượng cao để xây dựng các ứng dụng và dịch vụ web hiện đại. Framework này nổi tiếng nhờ sự linh hoạt, thiết kế module hóa và hiệu năng cao, phù hợp để phát triển từ website đơn giản đến ứng dụng doanh nghiệp phức tạp.
ServBay là môi trường phát triển web dành cho macOS và Windows, tích hợp sẵn PHP, nhiều máy chủ web (Caddy, Nginx), cơ sở dữ liệu (MySQL, PostgreSQL, MongoDB), dịch vụ bộ nhớ đệm (Redis, Memcached) cùng nhiều tiện ích dành cho lập trình viên. ServBay giúp cài đặt, quản lý các phần mềm này dễ dàng, thuận tiện cho việc phát triển các dự án PHP trên máy local.
Tài liệu này sẽ hướng dẫn bạn cách setup, khởi tạo và chạy dự án Zend Framework (Laminas) trong môi trường ServBay, cũng như cách tích hợp các dịch vụ database và cache mà ServBay cung cấp.
Yêu cầu trước khi bắt đầu
Trước khi thực hiện, bạn cần đảm bảo:
- Đã cài đặt ServBay: Bạn đã cài và chạy ServBay thành công trên macOS hoặc Windows. Nếu chưa, hãy truy cập Trang chủ ServBay để xem hướng dẫn tải và cài đặt.
- Các gói phần mềm ServBay: Đã cài đầy đủ các package cần thiết trên ServBay, bao gồm:
- Tối thiểu một phiên bản PHP (nên chọn PHP 8.x hoặc cao hơn – Zend Framework/Laminas thường yêu cầu PHP mới).
- Máy chủ web (Caddy hoặc Nginx).
- Composer (ServBay đã tích hợp sẵn).
- Dịch vụ cơ sở dữ liệu (MySQL, PostgreSQL) và dịch vụ cache (Memcached, Redis) bạn dự định sử dụng. Bạn có thể kích hoạt các dịch vụ này ngay trên bảng điều khiển ServBay.
Tạo dự án Zend Framework
ServBay khuyến nghị lưu trữ tất cả dự án website tại các thư mục sau, giúp việc tự động quản lý và cấu hình website:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
Truy cập thư mục gốc website
Mở Terminal và điều hướng tới thư mục gốc được ServBay khuyến nghị:
macOS:
bashcd /Applications/ServBay/www
1Windows:
cmdcd C:\ServBay\www
1Tạo project bằng Composer
Composer đã được tích hợp sẵn bởi ServBay. Sử dụng lệnh
create-project
để tạo ứng dụng Zend Framework (Laminas skeleton application) mới trong thư mục con tên làservbay-zend-app
:bashcomposer create-project laminas/laminas-skeleton-application servbay-zend-app
1Lệnh này sẽ tải ứng dụng mẫu của Laminas về thư mục
servbay-zend-app
và cài đặt đầy đủ các phụ thuộc cần thiết.Truy cập thư mục dự án
Chuyển vào thư mục dự án vừa khởi tạo:
bashcd servbay-zend-app
1
Cấu hình máy chủ web
Để truy cập dự án Zend Framework qua trình duyệt, bạn cần cấu hình lại website trong ServBay.
- Mở bảng điều khiển ServBay: Khởi động ứng dụng ServBay.
- Đi tới phần Website: Chọn thẻ Website (Websites) trên giao diện chính.
- Thêm website mới: Nhấn nút
+
ở góc trái bên dưới để thêm website. - Điền thông tin website:
- Tên (Name): Đặt tên dễ nhận biết, ví dụ
My Zend Dev Site
. - Tên miền (Domain): Chọn tên miền bạn muốn truy cập trên local. Để tránh trùng với domain thực, nên dùng đuôi
.local
hoặc.test
nhưservbay-zend-test.local
. ServBay sẽ tự động cấu hình DNS local. - Kiểu website (Website Type): Chọn
PHP
. - Phiên bản PHP (PHP Version): Chọn phiên bản PHP mong muốn (ví dụ
8.3
). Đảm bảo phiên bản này đã cài đặt và bật trên ServBay. - Thư mục gốc website (Document Root): Chọn thư mục
public
của dự án, vì file khởi độngindex.php
của Zend Framework nằm tại đó:/Applications/ServBay/www/servbay-zend-app/public
.
- Tên (Name): Đặt tên dễ nhận biết, ví dụ
- Lưu & khởi động lại: Nhấn Save. ServBay sẽ yêu cầu xác nhận áp dụng thay đổi. Nhấn xác nhận để cấu hình được cập nhật và website hoạt động.
Tham khảo thêm hướng dẫn chi tiết trong thêm website đầu tiên trong tài liệu ServBay.
Ví dụ "Hello ServBay!" cơ bản
Sau đây, ta sẽ sửa code của dự án để khi truy cập URL gốc (/
), website sẽ hiển thị "Hello ServBay!".
Cấu hình route và controller (
module.config.php
)Sửa file
module/Application/config/module.config.php
ở thư mục gốc dự án, đảm bảo có cấu hình router và controller như sau: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', ], ], ], // ... Các route khác ], ], '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', ], ], // ... Các cấu hình khác ];
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
49Lưu ý: Đây là phần cấu hình của file
module.config.php
, bạn hãy chèn hoặc cập nhật lại cho phù hợp với cấu trúc hiện có của dự án.Tạo hoặc sửa controller (
IndexController.php
)Sửa hoặc tạo file
module/Application/src/Controller/IndexController.php
, đảm bảo phương thứcindexAction
trả ra ViewModel với thông điệp:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; class IndexController extends AbstractActionController { /** * Action mặc định hiển thị trang chào mừng. */ public function indexAction() { // Trả ViewModel, truyền biến 'message' cho view return new ViewModel([ 'message' => 'Hello ServBay!', ]); } // ... Các action khác }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24Tạo hoặc sửa view (
index.phtml
)Sửa hoặc tạo file
module/Application/view/application/index/index.phtml
để nhận và hiển thị biếnmessage
từ controller:php<h1><?php echo $this->message; ?></h1>
1Sử dụng view helper
$this->message
của Laminas để truy cập dữ liệu truyền từ controller.
Truy cập website
Mở trình duyệt và truy cập vào domain đã cấu hình trên ServBay, ví dụ https://servbay-zend-test.local
.
Nếu mọi thứ đã setup đúng, bạn sẽ thấy dòng chữ Hello ServBay!
xuất hiện. Điều này chứng tỏ dự án Zend Framework đã chạy thành công trên môi trường ServBay.
Ví dụ tích hợp database và cache
ServBay cung cấp nhiều dịch vụ cơ sở dữ liệu và cache. Các ví dụ dưới đây sẽ trình bày cách kết nối và sử dụng Memcached, Redis, MySQL, PostgreSQL trong dự án Zend Framework.
Lưu ý: Các ví dụ này là độc lập, nhằm mục đích trình diễn. Trong thực tế, bạn sẽ lựa chọn loại database và cache phù hợp với dự án, quản lý kết nối thông qua Dependency Injection. Đảm bảo đã kích hoạt các package tương ứng (MySQL, PostgreSQL, Memcached, Redis) trên ServBay trước khi chạy demo.
Ví dụ thao tác database - Tạo bảng
Đầu tiên, bạn sẽ thao tác tạo một bảng dữ liệu đơn giản trong database bằng component Laminas DB.
Cài đặt component Laminas DB
Tại thư mục gốc dự án, dùng Composer cài đặt component db của Laminas:
bashcomposer require laminas/laminas-db
1Tạo database thủ công
Trước khi thử ví dụ, hãy tạo database tên
servbay_zend_app
trong dịch vụ database bạn chọn. Truy cập công cụ quản lý database qua ServBay (phpMyAdmin, pgAdmin, MongoDB Compass...). Mặc định user cho MySQL/MariaDB làroot
, password làpassword
; user cho PostgreSQL cũng làroot
và password làpassword
.Viết script tạo bảng
Tạo file PHP (ví dụ
create_users_table.php
ở thư mục gốc), với code sau để tạo bảngusers
:php<?php // create_users_table.php use Laminas\Db\Adapter\Adapter; use Laminas\Db\Sql\Sql; // Giả sử dùng MySQL hoặc MariaDB $adapter = new Adapter([ 'driver' => 'Pdo_Mysql', // Hoặc 'Pdo_Pgsql' 'database' => 'servbay_zend_app', 'username' => 'root', 'password' => 'password', // Mật khẩu mặc định ServBay 'hostname' => '127.0.0.1', // 'port' => 3306, // Port MySQL mặc định // 'port' => 5432, // Port PostgreSQL mặc định ]); $sql = new Sql($adapter); // Định nghĩa SQL tạo bảng users $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 "Thực thi SQL:\n"; echo $sql->buildSqlString($create, $adapter->getPlatform()) . "\n"; try { // Chạy truy vấn SQL $adapter->query( $sql->buildSqlString($create, $adapter->getPlatform()), Adapter::QUERY_MODE_EXECUTE ); echo "Tạo bảng 'users' thành công.\n"; } catch (\Exception $e) { echo "Lỗi tạo bảng: " . $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
38Lưu ý: Đây chỉ là ví dụ script thủ công. Trong thực tế nên sử dụng Laminas Migrations để quản lý phiên bản schema.
Chạy script trên bằng PHP CLI:
bashphp create_users_table.php
1
Ví dụ tích hợp MySQL
Demo cách truy vấn MySQL trong controller của Zend Framework.
Cấu hình kết nối MySQL
Sửa file
config/autoload/global.php
, bổ sung cấu hình database:php<?php // config/autoload/global.php return [ 'db' => [ 'driver' => 'Pdo_Mysql', 'database' => 'servbay_zend_app', // Database đã tạo trước đó 'username' => 'root', // User mặc định ServBay 'password' => 'password', // Mật khẩu mặc định ServBay 'hostname' => '127.0.0.1', 'port' => 3306, // Port MySQL mặc định 'charset' => 'utf8mb4', ], // ... Các cấu hình khác ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14Cấu hình factory controller (
module.config.php
)Để inject
Laminas\Db\Adapter\Adapter
vào controller, cần định nghĩa factory choIndexController
. Thay thế hoặc thêm vào phần controllers trongmodule/Application/config/module.config.php
:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\ServiceManager\Factory\InvokableFactory; use Laminas\Db\Adapter\AdapterInterface; return [ // ... Các cấu hình khác 'controllers' => [ 'factories' => [ Controller\IndexController::class => function($container) { // Lấy adapter từ Service Manager $adapter = $container->get(AdapterInterface::class); // Tạo controller và inject adapter return new Controller\IndexController($adapter); }, ], ], 'service_manager' => [ 'aliases' => [ // Alias cho AdapterInterface về Adapter thực tế AdapterInterface::class => 'Laminas\Db\Adapter\Adapter', ], 'factories' => [ 'Laminas\Db\Adapter\Adapter' => \Laminas\Db\Adapter\AdapterServiceFactory::class, ], ], // ... Các cấu hình khác ];
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
30Lưu ý: Cần ghép vào cấu hình có sẵn của project phù hợp.
Thêm route cho MySQL demo (
module.config.php
)Thêm route mới vào file
module/Application/config/module.config.php
:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... Các route khác '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', ], ], ], ], ], // ... Các cấu hình khác ];
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
34Thêm method controller (IndexController.php)
Sửa file
module/Application/src/Controller/IndexController.php
, xây dựng hàm khởi tạo nhận adapter, đồng thời bổ sung 2 action: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 mặc định. */ public function indexAction() { return new ViewModel([ 'message' => 'Hello ServBay!', ]); } /** * Action thêm user mới vào bảng 'users' qua MySQL. */ public function mysqlAddAction() { $sql = new Sql($this->adapter); $insert = $sql->insert('users') ->values([ 'name' => 'ServBay Demo User', 'email' => 'demo-mysql@servbay.test', ]); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); $message = $result->getAffectedRows() > 0 ? 'Thêm user MySQL thành công.' : 'Thêm user MySQL thất bại.'; return new ViewModel([ 'message' => $message, ]); } /** * Action liệt kê toàn bộ user từ bảng 'users' qua MySQL. */ 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; } // Chuyển result về string JSON để hiển thị return new ViewModel([ 'users' => json_encode($users, JSON_PRETTY_PRINT), ]); } // ... Các action khác }
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
76Tạo file view
Tạo file
module/Application/view/application/index/mysql-add.phtml
:php<h1><?php echo $this->message; ?></h1>
1Tạo file
module/Application/view/application/index/mysql.phtml
:php<h1>MySQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2Truy cập demo MySQL
Bật dịch vụ MySQL trên ServBay. Truy cập
https://servbay-zend-test.local/mysql-add
để thêm user mới. Kết quả sẽ là "Thêm user MySQL thành công." Truy cậphttps://servbay-zend-test.local/mysql
để xem dữ liệu bảngusers
dạng JSON.
Ví dụ tích hợp PostgreSQL
Demo cách truy vấn PostgreSQL trong controller.
Cấu hình kết nối PostgreSQL
Sửa lại db config trong file
config/autoload/global.php
: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, // Port PostgreSQL mặc định ], // ... Các cấu hình khác ];
1
2
3
4
5
6
7
8
9
10
11
12
13Cấu hình factory controller
Tương tự phần MySQL phía trên, đảm bảo đã cấu hình inject Adapter thông qua factory cho IndexController.
Thêm route cho PostgreSQL demo
Bổ sung route vào file
module/Application/config/module.config.php
:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... Các route khác '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', ], ], ], ], ], // ... Các cấu hình khác ];
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
34Thêm method controller
Trong file
module/Application/src/Controller/IndexController.php
, bổ sung các method sau: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; } // ... Các action hiện có /** * Action thêm user vào bảng 'users' qua PostgreSQL. */ public function pgsqlAddAction() { $sql = new Sql($this->adapter); $insert = $sql->insert('users') ->values([ 'name' => 'ServBay Demo User', 'email' => 'demo-pgsql@servbay.test', ]); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); $message = $result->getAffectedRows() > 0 ? 'Thêm user PostgreSQL thành công.' : 'Thêm user PostgreSQL thất bại.'; return new ViewModel([ 'message' => $message, ]); } /** * Action lấy toàn bộ user từ bảng 'users' qua PostgreSQL. */ 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; } 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
65Tạo file view
Tạo file
module/Application/view/application/index/pgsql-add.phtml
:php<h1><?php echo $this->message; ?></h1>
1Tạo file
module/Application/view/application/index/pgsql.phtml
:php<h1>PostgreSQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2Truy cập demo PostgreSQL
Bật dịch vụ PostgreSQL trên ServBay. Truy cập
https://servbay-zend-test.local/pgsql-add
để thêm user mới. Truy cậphttps://servbay-zend-test.local/pgsql
để xem dữ liệu bảngusers
.
Ví dụ tích hợp Memcached
Demo cách sử dụng Memcached làm bộ nhớ đệm dữ liệu trong controller.
Cài đặt Memcached adapter
Thêm Laminas Cache adapter Memcached vào
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
7Chạy lệnh cài đặt:
bashcomposer update
1ServBay đã cài sẵn extension PHP
memcached
.Thêm route cho Memcached
Sửa file
module/Application/config/module.config.php
để thêm route cho demo Memcached:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... Các route khác 'memcached' => [ 'type' => Literal::class, 'options' => [ 'route' => '/memcached', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'memcached', ], ], ], ], ], // ... Các cấu hình khác ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24Thêm method controller cho Memcached
Thêm code sau vào class
IndexController
: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 { // ... Các action khác /** * Action demo dùng Memcached. */ public function memcachedAction() { // Tạo instance Memcached cache $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'memcached', 'options' => [ 'servers' => [ ['127.0.0.1', 11211], ], 'ttl' => 300, // 5 phút ], ], 'plugins' => [ 'serializer', 'exception_handler' => ['throw_exceptions' => false], ], ]); $cacheKey = 'my_memcached_data'; $cachedData = $cache->getItem($cacheKey, $success); if (!$success) { // Nếu cache chưa có $cachedData = 'Hello Memcached! (Dữ liệu gốc, cache lúc ' . date('Y-m-d H:i:s') . ')'; $cache->setItem($cacheKey, $cachedData); $cachedData .= ' - CACHE MISS'; } else { // Nếu cache đã có sẵn $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
55Tạo file view
Tạo file
module/Application/view/application/index/memcached.phtml
:php<h1>Ví dụ Memcached</h1> <p><?php echo $this->message; ?></p>
1
2Truy cập demo Memcached
Bật dịch vụ Memcached trên ServBay. Truy cập
https://servbay-zend-test.local/memcached
. Lần truy cập đầu thấy dòng "CACHE MISS" (lấy từ nguồn), các lần sau trong 300s sẽ thấy "CACHE HIT".
Ví dụ tích hợp Redis
Demo cách dùng Redis làm bộ nhớ đệm hoặc lưu trữ dữ liệu trong controller.
Cài đặt Redis adapter
Thêm vào
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
8Chạy lệnh cài đặt:
bashcomposer update
1ServBay đã cài sẵn extension PHP
redis
.Thêm route cho Redis
Sửa file
module/Application/config/module.config.php
thêm route:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... Các route khác 'redis' => [ 'type' => Literal::class, 'options' => [ 'route' => '/redis', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'redis', ], ], ], ], ], // ... Các cấu hình khác ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24Thêm method controller cho Redis
Thêm vào class
IndexController
: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 { // ... Các action khác /** * Action demo dùng Redis. */ public function redisAction() { // Tạo instance Redis cache $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'redis', 'options' => [ 'server' => [ 'host' => '127.0.0.1', 'port' => 6379, ], 'ttl' => 300, // 5 phút ], ], 'plugins' => [ 'serializer', 'exception_handler' => ['throw_exceptions' => false], ], ]); $cacheKey = 'my_redis_data'; $cachedData = $cache->getItem($cacheKey, $success); if (!$success) { // Cache chưa có $cachedData = 'Hello Redis! (Dữ liệu gốc, cache lúc ' . date('Y-m-d H:i:s') . ')'; $cache->setItem($cacheKey, $cachedData); $cachedData .= ' - CACHE MISS'; } else { // Có cache $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
56Tạo file view
Tạo file
module/Application/view/application/index/redis.phtml
:php<h1>Ví dụ Redis</h1> <p><?php echo $this->message; ?></p>
1
2Truy cập demo Redis
Bật dịch vụ Redis trên ServBay. Truy cập
https://servbay-zend-test.local/redis
. Lần đầu thấy "CACHE MISS", các lần tiếp theo trong 300s sẽ thấy "CACHE HIT".
Tổng kết
Sau các bước trên, bạn đã setup thành công dự án Zend Framework (Laminas) trên môi trường phát triển local ServBay, cấu hình máy chủ web trỏ về thư mục công khai của dự án, đồng thời tích hợp database MySQL, PostgreSQL cũng như dịch vụ cache Memcached, Redis.
ServBay giúp đơn giản hóa việc triển khai môi trường lập trình local, cho phép tập trung phát triển code và dự án. Tận dụng sức mạnh từ các package sẵn có cùng khả năng cấu hình linh hoạt, bạn sẽ dễ dàng mô phỏng môi trường production ngay trên máy cá nhân, tăng hiệu suất và kiểm soát phát triển dự án một cách chuyên nghiệp.