Cipta & Jalankan Projek Zend Framework (Laminas) Dalam ServBay
Pengenalan
Zend Framework (kini sebahagian daripada Laminas Project) ialah rangka kerja PHP sumber terbuka yang kukuh, menawarkan pelbagai komponen berorientasikan objek berkualiti tinggi untuk membina aplikasi dan perkhidmatan Web moden. Ia terkenal dengan fleksibiliti, reka bentuk modular, dan prestasi tinggi—sesuai untuk membangunkan laman web mudah hingga aplikasi peringkat perusahaan kompleks.
ServBay ialah persekitaran pembangunan Web tempatan untuk macOS, menggabungkan PHP, pelbagai pelayan web (seperti Caddy dan Nginx), pangkalan data (seperti MySQL, PostgreSQL, MongoDB), perkhidmatan cache (seperti Redis, Memcached), serta set alat pembangunan lain. ServBay menyediakan cara mudah untuk mengkonfigurasi dan mengurus semua perisian ini secara terpusat, menjadikan persediaan dan pengurusan projek PHP tempatan sangat pantas dan mudah.
Dokumen ini akan membimbing anda mencipta dan menjalankan projek Zend Framework (Laminas) di ServBay, serta contoh integrasi pangkalan data dan perkhidmatan cache yang disediakan oleh ServBay.
Prasyarat
Sebelum bermula, sila pastikan perkara berikut telah disediakan:
- Pemasangan ServBay: Anda telah berjaya memasang dan menjalankan ServBay di macOS. Jika belum, lawati Laman Web Rasmi ServBay untuk panduan muat turun dan pemasangan.
- Pakej ServBay: Pastikan semua pakej perisian yang diperlukan telah dipasang dan dijalankan dalam ServBay, termasuk:
- Sekurang-kurangnya satu versi PHP (disyorkan PHP 8.x atau lebih baharu, kerana versi baharu Zend Framework / Laminas memerlukan versi PHP yang moden).
- Pelayan Web (Caddy atau Nginx).
- Composer (biasanya disertakan bersama ServBay).
- Perkhidmatan pangkalan data (contoh: MySQL, PostgreSQL) dan cache (contoh: Memcached, Redis) mengikut keperluan projek anda. Anda boleh mengaktifkan perkhidmatan ini terus melalui panel kawalan ServBay.
Cipta Projek Zend Framework
ServBay mengesyorkan agar semua projek laman web anda diletakkan di bawah direktori /Applications/ServBay/www
untuk urusan konfigurasi dan pengurusan laman yang automatik.
Navigasi ke Root Projek Laman Web
Buka Terminal dan arahkan ke direktori root laman web yang dicadangkan oleh ServBay:
bashcd /Applications/ServBay/www
1Cipta Projek Dengan Composer
Composer telah pun disertakan bersama pemasangan ServBay. Gunakan arahan
create-project
Composer untuk mencipta aplikasi kerangka asas Zend Framework (Laminas):bashcomposer create-project laminas/laminas-skeleton-application servbay-zend-app
1Ini akan memuat turun aplikasi kerangka asas Zend Framework ke dalam folder
servbay-zend-app
dan memasang semua kebergantungan yang perlu.Masuk ke Direktori Projek
Beralih ke direktori projek yang baru dicipta:
bashcd servbay-zend-app
1
Konfigurasi Pelayan Web
Agar laman Zend Framework anda dapat diakses dari pelayar, anda perlu konfigurasi laman web secara rasmi di ServBay.
- Buka Panel Kawalan ServBay: Jalankan aplikasi ServBay.
- Pergi ke Tetapan Website: Dalam panel kawalan ServBay, pilih tab Websites.
- Tambah Laman Baru: Klik ikon
+
di kiri bawah untuk menambah konfigurasi laman baru. - Isi Maklumat Website:
- Nama (Name): Berikan nama mudah untuk dikenalpasti, seperti
My Zend Dev Site
. - Domain (Domain): Masukkan domain yang akan digunakan di pelayar. Untuk mengelak konflik dengan domain sebenar, gunakan akhiran
.local
atau.test
, contoh:servbay-zend-test.local
. ServBay akan menguruskan resolusi DNS tempatan secara automatik. - Jenis Website (Website Type): Pilih
PHP
. - Versi PHP (PHP Version): Pilih versi PHP yang dipasang dan akan digunakan untuk laman ini (contoh:
8.3
). - Root Website (Document Root): Ini ialah lokasi di mana fail utama Zend Framework dibuka iaitu
index.php
dalam folderpublic
projek anda, cth:/Applications/ServBay/www/servbay-zend-app/public
.
- Nama (Name): Berikan nama mudah untuk dikenalpasti, seperti
- Simpan & Muat Semula: Klik butang Save. ServBay akan meminta pengesahan untuk memuat semula konfigurasi pelayan web, lalu laman anda menjadi aktif.
Panduan terperinci boleh dirujuk pada dokumen ServBay Menambah Laman Web Pertama.
Contoh Asas "Hello ServBay!"
Sekarang, kita akan ubah kod projek supaya akses ke URL root (/
) akan memaparkan "Hello ServBay!".
Konfigurasi Routing & Controller (module.config.php)
Edit fail
module/Application/config/module.config.php
dalam root projek anda. Pastikan mengandungi konfigurasi berikut: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', ], ], ], // ... konfigurasi routes lain ], ], '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', ], ], // ... konfigurasi lain ];
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
49Nota: Kod di atas merupakan sebahagian dari
module.config.php
. Gabungkan konfigurasi ini dengan tetapan sedia ada dan pastikan rujukan'home'
danController\IndexController::class
telah ditakrifkan.Cipta atau Ubah Controller (IndexController.php)
Sunting atau cipta fail
module/Application/src/Controller/IndexController.php
. Pastikan kaedahindexAction
mengembalikan ViewModel dengan mesej berikut:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; class IndexController extends AbstractActionController { /** * Default action to display the welcome page. */ public function indexAction() { // Kembalikan ViewModel serta variable 'message' ke view return new ViewModel([ 'message' => 'Hello ServBay!', ]); } // ... kaedah action lain }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24Ubah Atau Cipta Fail View (index.phtml)
Sunting atau cipta fail
module/Application/view/application/index/index.phtml
untuk menerima dan paparkanmessage
dari controller:php<h1><?php echo $this->message; ?></h1>
1Di sini
$this->message
digunakan (view helper Zend Framework) untuk paparkan data dari controller.
Akses Laman Web
Buka pelayar web dan lawati domain yang anda konfigurasikan dalam ServBay, contohnya https://servbay-zend-test.local
.
Jika semua konfigurasi betul, anda akan melihat paparan "Hello ServBay!". Ini menandakan projek Zend Framework anda telah berjaya dijalankan di ServBay.
Contoh Integrasi Pangkalan Data & Cache
ServBay menyokong pelbagai pangkalan data dan cache. Di bawah adalah contoh integrasi Memcached, Redis, MySQL dan PostgreSQL dalam projek Zend Framework anda.
Penting: Semua contoh berikut adalah demonstrasi kendiri. Dalam aplikasi sebenar, anda digalakkan untuk memilih satu jenis pangkalan data serta satu atau beberapa perkhidmatan cache yang sesuai, dengan pengurusan sambungan menggunakan teknik seperti dependency injection. Pastikan perkhidmatan yang diperlukan telah diaktifkan (cth: MySQL, PostgreSQL, Memcached, Redis) dalam ServBay sebelum mencuba contoh berikut.
Contoh Interaksi Pangkalan Data - Cipta Jadual
Demonstrasi pertama ialah bagaimana berinteraksi dengan pangkalan data menggunakan komponen Laminas DB, khususnya untuk mencipta sebuah jadual ringkas. Kod berikut ialah contoh skrip penciptaan jadual yang boleh dijalankan secara manual, bukan menggunakan alat Migrations penuh.
Pasang Komponen Laminas DB
Jalankan arahan Composer di root projek:
bashcomposer require laminas/laminas-db
1Cipta Pangkalan Data Secara Manual
Sebelum anda jalankan contoh, cipta dahulu pangkalan data
servbay_zend_app
pada perkhidmatan pangkalan data (MySQL/PostgreSQL) dalam ServBay. Anda boleh guna alat pengurusan seperti phpMyAdmin, pgAdmin, atau MongoDB Compass dari panel kawalan ServBay. Nama pengguna lalai MySQL/MariaDB dan PostgreSQL di ServBay ialahroot
dengan kata laluanpassword
.Definisi & Jalankan Skrip Cipta Jadual (Contoh)
Cipta fail PHP, contoh
create_users_table.php
di root projek, dengan kod seperti berikut:php<?php // create_users_table.php use Laminas\Db\Adapter\Adapter; use Laminas\Db\Sql\Sql; // Anggap menggunakan MySQL atau MariaDB $adapter = new Adapter([ 'driver' => 'Pdo_Mysql', // atau 'Pdo_Pgsql' 'database' => 'servbay_zend_app', 'username' => 'root', 'password' => 'password', // Kata laluan lalai ServBay 'hostname' => '127.0.0.1', // 'port' => 3306, // Port lalai MySQL // 'port' => 5432, // Port lalai PostgreSQL ]); $sql = new Sql($adapter); // Definisikan SQL untuk cipta jadual 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 "Executing SQL:\n"; echo $sql->buildSqlString($create, $adapter->getPlatform()) . "\n"; try { // Jalankan 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
38Nota: Skrip ini hanya demonstrasi; dalam aplikasi sebenar, gunakan alat migration rasmi dari Laminas.
Jalankan skrip dengan PHP CLI untuk mencipta jadual:
bashphp create_users_table.php
1
Contoh Integrasi MySQL
Bagaimana cara menghubungkan dan melakukan pertanyaan data ke MySQL dalam controller Zend Framework.
Konfigurasi Sambungan Database
Edit fail
config/autoload/global.php
, tambah/mengubah konfigurasi MySQL seperti di bawah:php<?php // config/autoload/global.php return [ 'db' => [ 'driver' => 'Pdo_Mysql', 'database' => 'servbay_zend_app', // Pastikan database telah wujud 'username' => 'root', // Nama pengguna lalai ServBay 'password' => 'password', // Kata laluan lalai 'hostname' => '127.0.0.1', 'port' => 3306, // Port lalai MySQL 'charset' => 'utf8mb4', ], // ... konfigurasi global lain ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14Konfigurasi Factory Controller (module.config.php)
Untuk suntik
Laminas\Db\Adapter\Adapter
ke dalam controller, definisikan factory dalammodule/Application/config/module.config.php
di bahagiancontrollers
. Jika sudah adaInvokableFactory
untukIndexController
, gantikan dengan factory berikut:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\ServiceManager\Factory\InvokableFactory; use Laminas\Db\Adapter\AdapterInterface; return [ // ... konfigurasi lain 'controllers' => [ 'factories' => [ Controller\IndexController::class => function($container) { // Dapatkan adapter DB dari Service Manager $adapter = $container->get(AdapterInterface::class); return new Controller\IndexController($adapter); }, ], ], 'service_manager' => [ 'aliases' => [ // Alias interface ke Adapter sebenar AdapterInterface::class => 'Laminas\Db\Adapter\Adapter', ], 'factories' => [ 'Laminas\Db\Adapter\Adapter' => \Laminas\Db\Adapter\AdapterServiceFactory::class, ], ], // ... konfigurasi lain ];
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
29Nota: Gabungkan kod ini ke konfigurasi sedia ada anda.
Konfigurasi Routing (module.config.php)
Tambahkan routes baru untuk contoh MySQL dalam fail yang sama:
php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... routes sedia ada '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', ], ], ], ], ], // ... konfigurasi lain ];
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
34Tambah Kaedah dalam Controller (IndexController.php)
Dalam fail
module/Application/src/Controller/IndexController.php
, tambah constructor untuk menerima Adapter serta kaedah bagi demo tambah dan paparan MySQL: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; } /** * Default action to display the welcome page. */ public function indexAction() { return new ViewModel([ 'message' => 'Hello ServBay!', ]); } /** * Action untuk tambah user ke tabel 'users' (MySQL). */ 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, ]); } /** * Action untuk paparkan semua user dalam 'users' (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; } // Hantar hasil dalam format JSON ke view return new ViewModel([ 'users' => json_encode($users, JSON_PRETTY_PRINT), ]); } // ... action lain }
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
76Cipta Fail View
module/Application/view/application/index/mysql-add.phtml
:php<h1><?php echo $this->message; ?></h1>
1module/Application/view/application/index/mysql.phtml
:php<h1>MySQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2Akses Contoh MySQL
Pastikan servis MySQL di ServBay berjalan. Lawati
https://servbay-zend-test.local/mysql-add
untuk menambah user. Anda akan melihat mesej kejayaan. Lawatihttps://servbay-zend-test.local/mysql
untuk melihat senarai user (dalam format JSON).
Contoh Integrasi PostgreSQL
Sama seperti MySQL, contoh integrasi PostgreSQL dalam controller Zend Framework.
Konfigurasi Database
Edit
config/autoload/global.php
untuk tetapkan 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, ], // ... konfigurasi global lain ];
1
2
3
4
5
6
7
8
9
10
11
12
13Konfigurasi Factory Controller
Sekiranya anda telah mengubah factory controller seperti demo MySQL, abaikan langkah ini.
Konfigurasi Routing
Tambah routes berikut dalam
module.config.php
:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... routes sedia ada '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', ], ], ], ], ], // ... konfigurasi lain ];
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
34Tambah Kaedah Controller
Sunting
IndexController.php
, tambahpgsqlAddAction
danpgsqlAction
: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 sedia ada /** * Action tambah user ke 'users' (PostgreSQL). */ 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, ]); } /** * Paparkan semua user dari 'users' (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
65Cipta Fail View
module/Application/view/application/index/pgsql-add.phtml
:php<h1><?php echo $this->message; ?></h1>
1module/Application/view/application/index/pgsql.phtml
:php<h1>PostgreSQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2Akses Contoh PostgreSQL
Pastikan PostgreSQL dalam ServBay telah berjalan. Lawati
https://servbay-zend-test.local/pgsql-add
untuk tambah user, kemudian lihat senarai denganhttps://servbay-zend-test.local/pgsql
.
Contoh Integrasi Memcached
Demo menyimpan dan mendapatkan data menggunakan Memcached dalam controller Zend Framework.
Pasang Adapter Memcached
Tambah keperluan composer berikut:
json// composer.json { "require": { "laminas/laminas-skeleton-application": "^1.0", "laminas/laminas-cache-storage-adapter-memcached": "^2.0" // ... keperluan lain }, // ... konfigurasi lain }
1
2
3
4
5
6
7
8
9Jalankan:
bashcomposer update
1ServBay telah tersedia dengan PHP extension
memcached
.Tambah Routing (module.config.php)
Dalam
module.config.php
, tambah route baru:php<?php namespace Application; use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... routes lain 'memcached' => [ 'type' => Literal::class, 'options' => [ 'route' => '/memcached', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'memcached', ], ], ], ], ], // ... konfigurasi lain ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23Tambah Kaedah Controller
Dalam
IndexController.php
, tambah: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 { // ... constructor & actions lain /** * Demonstrasi penggunaan Memcached. */ public function memcachedAction() { // Konfigurasi Memcached di 127.0.0.1:11211 $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'memcached', 'options' => [ 'servers' => [ ['127.0.0.1', 11211], ], 'ttl' => 300, // 300 saat ], ], '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
53Cipta Fail View
module/Application/view/application/index/memcached.phtml
:php<h1>Memcached Example</h1> <p><?php echo $this->message; ?></p>
1
2Akses Contoh Memcached
Pastikan perkhidmatan Memcached berjalan, kemudian lawati
https://servbay-zend-test.local/memcached
. Kali pertama akses akan paparkan "CACHE MISS"; selanjutnya, dalam masa 5 minit, anda akan lihat "CACHE HIT".
Contoh Integrasi Redis
Cara menggunakan Redis untuk cache/data storage dalam controller.
Pasang Adapter Redis
Tambah keperluan composer:
json// composer.json { "require": { "laminas/laminas-skeleton-application": "^1.0", "laminas/laminas-cache-storage-adapter-redis": "^2.0", "ext-redis": "*" // ... keperluan lain }, // ... konfigurasi lain }
1
2
3
4
5
6
7
8
9
10Jalankan:
bashcomposer update
1Extension PHP
redis
telah tersedia dalam ServBay.Tambah Routing (module.config.php)
Tambah route baru dalam fail konfigurasi:
php<?php use Laminas\Router\Http\Literal; return [ 'router' => [ 'routes' => [ // ... routes lain 'redis' => [ 'type' => Literal::class, 'options' => [ 'route' => '/redis', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'redis', ], ], ], ], ], // ... konfigurasi lain ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21Tambah Kaedah Controller
Dalam
IndexController.php
, tambah: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 { // ... kaedah lain /** * Demonstrasi penggunaan Redis. */ public function redisAction() { $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'redis', 'options' => [ 'server' => [ 'host' => '127.0.0.1', 'port' => 6379, ], '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
53Cipta Fail View
module/Application/view/application/index/redis.phtml
:php<h1>Redis Example</h1> <p><?php echo $this->message; ?></p>
1
2Akses Contoh Redis
Pastikan perkhidmatan Redis berjalan, lalu lawati
https://servbay-zend-test.local/redis
. Pertama kali akses akan dapat "CACHE MISS", seterusnya untuk 5 minit, "CACHE HIT".
Rumusan
Dengan langkah-langkah di atas, anda telah berjaya mencipta, mengkonfigurasikan, dan menjalankan projek Zend Framework (Laminas) di persekitaran pembangunan tempatan ServBay. Anda juga telah mempelajari cara menggunakan ciri laman web dalam ServBay untuk konfigurasi pelayan web, serta mengintegrasikan perkhidmatan MySQL, PostgreSQL, Memcached, dan Redis dalam projek anda.
ServBay memudahkan pembangunan tempatan, membolehkan anda fokus kepada penulisan kod dan pembangunan ciri, sambil meniru suasana produksi dengan mudah — meningkatkan kecekapan serta kemudahan pembangunan projek web PHP moden.