Creating and Running a Zend Framework (Laminas) Project in ServBay
Overview
Zend Framework (now part of the Laminas Project) is a robust open-source PHP framework that provides a collection of high-quality, object-oriented components for building modern web applications and services. Known for its flexibility, modular architecture, and high performance, it's an excellent choice for building anything from simple websites to complex enterprise-grade solutions.
ServBay is a local web development environment designed for macOS and Windows, integrating PHP, various web servers (such as Caddy and Nginx), databases (including MySQL, PostgreSQL, MongoDB), caching services (such as Redis and Memcached), and other developer tools. ServBay offers an easy way to configure and manage these packages, making it simple to set up and run PHP framework projects locally.
This document will walk you through creating and running a Zend Framework (Laminas) project within ServBay, and demonstrate how to integrate ServBay's database and caching services.
Prerequisites
Before you begin, make sure you have:
- Installed ServBay: ServBay is successfully installed and running on your macOS or Windows machine. If not, visit the ServBay official website for download and installation instructions.
- Required ServBay Packages: The necessary software packages are installed and running within ServBay, including:
- At least one version of PHP (PHP 8.x or newer is recommended, as Zend Framework/Laminas requires modern PHP).
- A web server (Caddy or Nginx).
- Composer (usually bundled with ServBay).
- Your chosen database services (like MySQL, PostgreSQL) and caching services (like Memcached, Redis). These can be started easily via the ServBay dashboard.
Creating a Zend Framework Project
ServBay recommends organizing your website projects in the following directories for easy management and automated configuration:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
Navigate to the Website Root Directory
Open your terminal application and go to the ServBay recommended website root:
macOS:
bashcd /Applications/ServBay/www
1Windows:
cmdcd C:\ServBay\www
1Create Project Using Composer
Composer comes bundled with ServBay, so you don't need to install it separately. Use the Composer
create-project
command to set up a new Zend Framework (Laminas skeleton application) project. We'll create the project in a subdirectory calledservbay-zend-app
:bashcomposer create-project laminas/laminas-skeleton-application servbay-zend-app
1This command downloads the Zend Framework (Laminas) skeleton application to the
servbay-zend-app
directory and installs all necessary dependencies.Enter the Project Directory
Move into your new project directory:
bashcd servbay-zend-app
1
Web Server Configuration
To access your Zend Framework project via the browser, you need to configure a website in ServBay.
- Open ServBay Dashboard: Launch the ServBay application.
- Go to Website Settings: Find and click the Websites tab in the ServBay dashboard.
- Add a New Website: Click the
+
button in the lower left to add a new website configuration. - Fill in Website Details:
- Name: Choose an easily recognizable name, e.g.,
My Zend Dev Site
. - Domain: Enter the domain name you want to use in your browser. To avoid conflicts with real domains, it's recommended to use a
.local
or.test
suffix, such asservbay-zend-test.local
. ServBay automatically configures local DNS resolution. - Website Type: Select
PHP
. - PHP Version: Choose the PHP version for this website (e.g.
8.3
). Make sure it's installed and running in ServBay. - Document Root: This is the directory your web server will serve. The entry file for Zend Framework is
index.php
in thepublic
directory, so set the document root to your project'spublic
folder:/Applications/ServBay/www/servbay-zend-app/public
.
- Name: Choose an easily recognizable name, e.g.,
- Save and Restart: Click Save. ServBay will prompt you to apply changes; after confirming, the web server will reload its configuration, activating your new site.
For more detailed instructions, refer to the ServBay documentation on Adding Your First Website.
Basic "Hello ServBay!" Example
Let's modify the project so that visiting the root URL (/
) displays "Hello ServBay!".
Set up Routing and Controller (module.config.php)
Edit your project's
module/Application/config/module.config.php
file. Ensure it contains the following routing and controller setup: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', ], ], ], // ... other route configurations ], ], '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', ], ], // ... other config ];
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
49Note: The above is a partial
module.config.php
snippet; you'll need to merge it into your existing configuration array. Make sure the'home'
route and factory forController\IndexController::class
are present.Create or Edit the Controller (IndexController.php)
Edit or create the file
module/Application/src/Controller/IndexController.php
. Make sure theindexAction
returns a ViewModel containing a message: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() { // Return a ViewModel and pass 'message' to the view return new ViewModel([ 'message' => 'Hello ServBay!', ]); } // ... other action methods }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24Create or Edit the View File (index.phtml)
Edit or create
module/Application/view/application/index/index.phtml
. This file will receive themessage
variable from the controller and display it:php<h1><?php echo $this->message; ?></h1>
1Here, the
$this->message
view helper in Zend Framework (Laminas) accesses controller data.
Accessing the Site
Open your browser and visit the domain you configured in ServBay, for example, https://servbay-zend-test.local
.
If everything is configured correctly, you'll see the page showing Hello ServBay!
. This confirms that your Zend Framework project is up and running in ServBay.
Database and Cache Integration Examples
ServBay offers various database and cache services. Below are examples of using Memcached, Redis, MySQL, and PostgreSQL in a Zend Framework project.
Important: The following database and cache demos are standalone examples. In real projects, you will usually select one database and one or more caching services as needed, and manage connections using dependency injection. To run these examples, ensure the relevant services (MySQL, PostgreSQL, Memcached, Redis) are started in ServBay.
Database Interaction Example - Creating a Table
Let's demonstrate interacting with a database using the Laminas DB component, including creating a simple table. The code sample shows how to manually define and execute a table creation operation, instead of using the full Laminas Migrations tool.
Install the Laminas DB component
In your project root, run Composer to install Laminas DB:
bashcomposer require laminas/laminas-db
1Manually Create a Database
Before running the demo, manually create a database called
servbay_zend_app
in your chosen database service within ServBay. You can use ServBay's database management tools (phpMyAdmin, pgAdmin, MongoDB Compass, etc.). ServBay default credentials: MySQL/MariaDB username:root
, password:password
. PostgreSQL username:root
, password:password
.Define and Execute Table Creation Script (Example)
Create a PHP file (e.g.,
create_users_table.php
in your project root or a temporary location) with the following code to define and execute ausers
table creation:php<?php // create_users_table.php use Laminas\Db\Adapter\Adapter; use Laminas\Db\Sql\Sql; // Assume you are using MySQL or MariaDB $adapter = new Adapter([ 'driver' => 'Pdo_Mysql', // or 'Pdo_Pgsql' 'database' => 'servbay_zend_app', 'username' => 'root', 'password' => 'password', // ServBay default password 'hostname' => '127.0.0.1', // 'port' => 3306, // MySQL default port // 'port' => 5432, // PostgreSQL default port ]); $sql = new Sql($adapter); // Define SQL to create the users table $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 { // Execute 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
38Note: This is a manually executed script example. In production, you would use Laminas Migrations to manage database schema versions.
Run this script via PHP CLI in your terminal (from the project root or where the script is located):
bashphp create_users_table.php
1
MySQL Integration Example
Demonstrates connecting to and querying MySQL from a Zend Framework controller.
Configure Database Connection
Edit
config/autoload/global.php
and configure MySQL connection details. If there's an existingdb
config, modify it; if not, add:php<?php // config/autoload/global.php return [ 'db' => [ 'driver' => 'Pdo_Mysql', 'database' => 'servbay_zend_app', // Make sure this DB exists 'username' => 'root', // ServBay default username 'password' => 'password', // ServBay default password 'hostname' => '127.0.0.1', 'port' => 3306, // MySQL default port 'charset' => 'utf8mb4', ], // ... other global config ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14Configure Controller Factory (module.config.php)
To inject
Laminas\Db\Adapter\Adapter
into your controller, redefine the factory forIndexController
. Edit thecontrollers
section inmodule/Application/config/module.config.php
. If you currently useInvokableFactory
, replace it with the following:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\ServiceManager\Factory\InvokableFactory; // Keep if used elsewhere use Laminas\Db\Adapter\AdapterInterface; // Add this use return [ // ... other config 'controllers' => [ 'factories' => [ Controller\IndexController::class => function($container) { // Get DB adapter from service manager $adapter = $container->get(AdapterInterface::class); // Create IndexController with injected adapter return new Controller\IndexController($adapter); }, // Add factories for other controllers as needed ], ], 'service_manager' => [ 'aliases' => [ // Alias for AdapterInterface to actual Adapter AdapterInterface::class => 'Laminas\Db\Adapter\Adapter', ], 'factories' => [ // Factory for Laminas\Db\Adapter\Adapter 'Laminas\Db\Adapter\Adapter' => \Laminas\Db\Adapter\AdapterServiceFactory::class, ], ], // ... other config ];
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
32Note: This is a partial config; merge into your
module.config.php
. Ensureservice_manager
section is set up correctly.Configure Routes (module.config.php)
Add new routes for MySQL demo in
module/Application/config/module.config.php
:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; // ... other use statements return [ 'router' => [ 'routes' => [ // ... existing routes (like 'home') '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', ], ], ], ], ], // ... other config (controllers, service_manager, view_manager) ];
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
35Add these under the
'routes'
key.Controller Methods (IndexController.php)
Edit
module/Application/src/Controller/IndexController.php
, add a constructor to accept the adapter, and implementmysqlAddAction
andmysqlAction
:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; use Laminas\Db\Adapter\AdapterInterface; // Add this use use Laminas\Db\Sql\Sql; // Add this use class IndexController extends AbstractActionController { private $adapter; // Add private property // Constructor to receive injected AdapterInterface 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 to add a user to 'users' table via MySQL. */ public function mysqlAddAction() { $sql = new Sql($this->adapter); $insert = $sql->insert('users') ->values([ 'name' => 'ServBay Demo User', 'email' => 'demo-mysql@servbay.test', // Example email ]); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); // Check insert result, return message $message = $result->getAffectedRows() > 0 ? 'MySQL User added successfully.' : 'Failed to add MySQL user.'; return new ViewModel([ 'message' => $message, ]); } /** * Action to fetch all users from 'users' table via 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; } // Pass results as JSON to the view return new ViewModel([ 'users' => json_encode($users, JSON_PRETTY_PRINT), ]); } // ... other action methods }
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
78Insert the constructor and these methods in your class.
Create View Files
Create
module/Application/view/application/index/mysql-add.phtml
:php<h1><?php echo $this->message; ?></h1>
1Create
module/Application/view/application/index/mysql.phtml
:php<h1>MySQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2Access the MySQL Demo
Ensure that MySQL is running in ServBay. First visit
https://servbay-zend-test.local/mysql-add
to add a user. You should see "MySQL User added successfully." Then visithttps://servbay-zend-test.local/mysql
to view data in the users table, which should include your recently added user (shown in JSON format).
PostgreSQL Integration Example
Demonstrates connecting to and querying PostgreSQL in a Zend Framework controller.
Configure Database Connection
Edit
config/autoload/global.php
and enter PostgreSQL connection details. Note: If you want to run both MySQL and PostgreSQL demos, you may need a more complex configuration or alternate setups. This example assumes you switch the'db'
config to PostgreSQL:php<?php // config/autoload/global.php return [ 'db' => [ 'driver' => 'Pdo_Pgsql', 'database' => 'servbay_zend_app', // Ensure this DB exists 'username' => 'root', // ServBay default username 'password' => 'password', // ServBay default password 'hostname' => '127.0.0.1', 'port' => 5432, // PostgreSQL default port ], // ... other global config ];
1
2
3
4
5
6
7
8
9
10
11
12
13Configure Controller Factory (module.config.php)
(Same as MySQL demo) Ensure
controllers
andservice_manager
inmodule.config.php
are set to inject the adapter. If you've already edited them for MySQL, no changes needed.Configure Routes (module.config.php)
Add new routes for the PostgreSQL demo:
php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; // ... other use statements return [ 'router' => [ 'routes' => [ // ... existing routes ('home', 'mysql-add', 'mysql') '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', ], ], ], ], ], // ... other config ];
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
35Add these under the
'routes'
key.Controller Methods (IndexController.php)
Edit
module/Application/src/Controller/IndexController.php
, addpgsqlAddAction
andpgsqlAction
: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; } // ... existing action methods (indexAction, mysqlAddAction, mysqlAction) /** * Action to add a user to 'users' table via PostgreSQL. */ public function pgsqlAddAction() { $sql = new Sql($this->adapter); $insert = $sql->insert('users') ->values([ 'name' => 'ServBay Demo User', 'email' => 'demo-pgsql@servbay.test', // Example email ]); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); // Check insert result, return message $message = $result->getAffectedRows() > 0 ? 'PostgreSQL User added successfully.' : 'Failed to add PostgreSQL user.'; return new ViewModel([ 'message' => $message, ]); } /** * Action to fetch all users from 'users' table via 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; } // Pass results as JSON to the view 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
67Add these methods to your controller class.
Create View Files
Create
module/Application/view/application/index/pgsql-add.phtml
:php<h1><?php echo $this->message; ?></h1>
1Create
module/Application/view/application/index/pgsql.phtml
:php<h1>PostgreSQL Users</h1> <pre><?php echo $this->users; ?></pre>
1
2Access the PostgreSQL Demo
Ensure PostgreSQL is running in ServBay. First visit
https://servbay-zend-test.local/pgsql-add
to add a user. You should see "PostgreSQL User added successfully." Then visithttps://servbay-zend-test.local/pgsql
to view data in the users table, shown in JSON format.
Memcached Integration Example
Shows how to use Memcached for data caching in a Zend Framework controller.
Install Memcached Adapter
In your project root, use Composer to install Laminas Cache's Memcached storage adapter:
json// composer.json { "require": { "laminas/laminas-skeleton-application": "^1.0", "laminas/laminas-cache-storage-adapter-memcached": "^2.0" // Add this line // ... other dependencies }, // ... other config }
1
2
3
4
5
6
7
8
9Then run
composer update
:bashcomposer update
1ServBay comes with the PHP
memcached
extension pre-installed.Configure Routes (module.config.php)
Add a new route for the Memcached example in
module/Application/config/module.config.php
:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; // ... other use statements return [ 'router' => [ 'routes' => [ // ... existing routes 'memcached' => [ 'type' => Literal::class, 'options' => [ 'route' => '/memcached', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'memcached', ], ], ], ], ], // ... other config ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25Add under routes.
Controller Method (IndexController.php)
Edit
module/Application/src/Controller/IndexController.php
and add thememcachedAction
method:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; // ... other use statements use Laminas\Cache\StorageFactory; // Add this use use Laminas\Cache\Storage\StorageInterface; // Add this use class IndexController extends AbstractActionController { // ... constructor and existing action methods /** * Action to demonstrate Memcached usage. */ public function memcachedAction() { // Create Memcached cache storage // ServBay's Memcached defaults to 127.0.0.1:11211 $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'memcached', 'options' => [ 'servers' => [ ['127.0.0.1', 11211], ], 'ttl' => 300, // Cache lifetime 300 seconds ], ], 'plugins' => [ // Common plugins like serializer 'serializer', 'exception_handler' => ['throw_exceptions' => false], ], ]); $cacheKey = 'my_memcached_data'; $cachedData = $cache->getItem($cacheKey, $success); // Try retrieving from cache if (!$success) { // Cache miss $cachedData = 'Hello Memcached! (Data from source, cached at ' . date('Y-m-d H:i:s') . ')'; $cache->setItem($cacheKey, $cachedData); // Store in cache $cachedData .= ' - CACHE MISS'; } else { // Cache hit $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
58Add this method to your class.
Create View File
Create
module/Application/view/application/index/memcached.phtml
:php<h1>Memcached Example</h1> <p><?php echo $this->message; ?></p>
1
2Access the Memcached Demo
Ensure Memcached is running in ServBay. Visit
https://servbay-zend-test.local/memcached
. On first visit, you should see a message with "CACHE MISS". Within the cache lifetime (300 seconds), subsequent visits will display "CACHE HIT" and the unchanged timestamp, showing the data is read from cache.
Redis Integration Example
Shows how to use Redis for data caching or storage in a Zend Framework controller.
Install Redis Adapter
In your project root, use Composer to install Laminas Cache's Redis adapter:
json// composer.json { "require": { "laminas/laminas-skeleton-application": "^1.0", "laminas/laminas-cache-storage-adapter-redis": "^2.0", // Add this line "ext-redis": "*" // Ensure PHP's redis extension is installed // ... other dependencies }, // ... other config }
1
2
3
4
5
6
7
8
9
10Then run
composer update
:bashcomposer update
1ServBay includes the PHP
redis
extension by default.Configure Routes (module.config.php)
Add a route for Redis example in
module/Application/config/module.config.php
:php<?php // module/Application/config/module.config.php namespace Application; use Laminas\Router\Http\Literal; // ... other use statements return [ 'router' => [ 'routes' => [ // ... existing routes 'redis' => [ 'type' => Literal::class, 'options' => [ 'route' => '/redis', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'redis', ], ], ], ], ], // ... other config ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25Add under routes.
Controller Method (IndexController.php)
Edit
module/Application/src/Controller/IndexController.php
and add theredisAction
method:php<?php declare(strict_types=1); namespace Application\Controller; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; // ... other use statements use Laminas\Cache\StorageFactory; // Add if not present use Laminas\Cache\Storage\StorageInterface; // Add if not present class IndexController extends AbstractActionController { // ... constructor and existing action methods /** * Action to demonstrate Redis usage. */ public function redisAction() { // Create Redis cache storage // ServBay's Redis defaults to 127.0.0.1:6379 $cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'redis', 'options' => [ 'server' => [ 'host' => '127.0.0.1', 'port' => 6379, // 'database' => 0, // Redis database index // 'password' => null, // Use if required ], 'ttl' => 300, // Cache lifetime 300 seconds ], ], 'plugins' => [ // Common cache plugins 'serializer', 'exception_handler' => ['throw_exceptions' => false], ], ]); $cacheKey = 'my_redis_data'; $cachedData = $cache->getItem($cacheKey, $success); // Try retrieving from cache if (!$success) { // Cache miss $cachedData = 'Hello Redis! (Data from source, cached at ' . date('Y-m-d H:i:s') . ')'; $cache->setItem($cacheKey, $cachedData); // Store in cache $cachedData .= ' - CACHE MISS'; } else { // Cache hit $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
59
60
61Add this method to your class.
Create View File
Create
module/Application/view/application/index/redis.phtml
:php<h1>Redis Example</h1> <p><?php echo $this->message; ?></p>
1
2Access the Redis Demo
Ensure Redis is running in ServBay. Visit
https://servbay-zend-test.local/redis
. On first visit, you should see a message with "CACHE MISS". Within cache lifetime (300 seconds), subsequent visits will display "CACHE HIT" and the unchanged timestamp, showing the data is read from cache.
Summary
By following these steps, you have successfully created, configured, and run a Zend Framework (Laminas) project in the ServBay local development environment. You learned how to use ServBay’s Website feature to configure the web server to point to your project’s public directory, and how to integrate and use MySQL, PostgreSQL databases, as well as Memcached and Redis cache services within your project.
ServBay streamlines building and managing your local development environment so you can focus more on coding and project development. Leveraging ServBay’s rich package selection and flexible configuration, you can easily simulate production environments locally and boost development productivity.