Creating and Running a Webman Project in ServBay
What is Webman?
Webman is a high-performance asynchronous PHP web framework based on Workerman, specially designed for building highly concurrent, high-performance web applications. Unlike traditional synchronous blocking frameworks, Webman uses an event-driven, asynchronous non-blocking I/O model, which allows it to excel at handling large volumes of concurrent requests. It offers a clean and user-friendly API, along with a flexible extension mechanism—making it ideal for building real-time applications, API services, microservices, and more.
Key Features and Advantages of Webman
- High Performance: Built on Workerman, leveraging event-driven and asynchronous non-blocking I/O, Webman can handle massive concurrent connections and delivers throughput far beyond traditional synchronous frameworks.
- Ease of Use: Offers a simple and intuitive API with rich features, so developers can get started quickly and build applications efficiently.
- Multi Protocol Support: Built-in support for a variety of common application layer protocols such as HTTP and WebSocket, making it easy to build different types of services.
- Flexible Extension: Easily extend framework functionality via Composer packages, plugins, and middleware.
- Low Resource Usage: Compared to the traditional web server + PHP-FPM model, Webman runs as a resident memory application, which results in lower resource consumption.
- Strong Community Support: Backed by an active development community and abundant documentation resources.
Webman helps developers quickly build high-performance, highly available web apps and APIs, especially well-suited for scenarios requiring high concurrency and low latency.
Create and Run a Simple Webman Project Using ServBay
This guide walks you step-by-step through using Webman within the ServBay local development environment to create and run a simple web project. We'll show how to install Webman, write basic routes and controllers, and integrate ServBay's database (MySQL, PostgreSQL) and caching services (Redis, Memcached).
TIP
ServBay recommends that all local website projects be placed in the /Applications/ServBay/www
directory for centralized management—such as configuring local websites (formerly known as "hosts").
Prerequisites
Before you begin, make sure you've completed the following:
- Install ServBay: ServBay must be successfully installed on your macOS system. ServBay provides an all-in-one local development environment, bundling PHP, Composer, MySQL, PostgreSQL, Redis, Memcached, and all software needed for this tutorial.
- Enable Required Packages: Open the ServBay control panel and ensure the following packages are installed and running:
- Your chosen PHP version (it is recommended to use a recent version, e.g., PHP 8.x)
- Composer (included with ServBay)
- MySQL
- PostgreSQL
- Redis
- Memcached
- Make sure you have enabled necessary PHP extensions including
memcached
,redis
,pdo_mysql
,pdo_pgsql
for your chosen PHP version. These common extensions are usually enabled by default in ServBay, but you can verify this in the PHP configuration within ServBay.
- Access to Terminal: You should be comfortable using the Terminal app on macOS.
Installing Webman
Verify Composer is Available
ServBay comes with Composer pre-installed, and Composer is available directly from the terminal. Run the following command to confirm:
bashcomposer --version
1If Composer's version info is displayed, Composer is ready to use.
Navigate to ServBay Web Directory
Open your terminal and change to the recommended ServBay website root directory:
bashcd /Applications/ServBay/www
1Create a Webman Project Using Composer
Use the Composer
create-project
command to install Webman in the specified directory. We'll call the projectservbay-webman-app
:bashcomposer create-project workerman/webman servbay-webman-app
1Composer will download Webman and its core dependencies from Packagist into the
servbay-webman-app
folder.Go Into the Project Directory
After installation completes, enter the new project directory:
bashcd servbay-webman-app
1Install Required Packages
To demonstrate database and caching functionality, we need to install additional Composer packages. Webman commonly uses
illuminate/database
(Laravel's database component),illuminate/redis
, and more. The-W
(--with-dependencies
) flag resolves dependency conflicts for compatibility.bashcomposer require -W illuminate/database illuminate/redis illuminate/pagination illuminate/events symfony/var-dumper
1This will install ORM, the Redis client, pagination, event dispatcher, and VarDumper for debugging.
Creating Databases and Tables
For the example code to work, we need to create the required database and users
table in both ServBay's MySQL and PostgreSQL databases. ServBay's default database user is root
, with password password
.
You can run the following SQL commands using database management tools provided by ServBay (such as phpMyAdmin or pgAdmin, accessible via the ServBay control panel) or via the command line.
Create Database
webman_app
- MySQL:sql
CREATE DATABASE IF NOT EXISTS webman_app CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
1 - PostgreSQL:sql
CREATE DATABASE webman_app;
1
- MySQL:
Create the
users
Table in thewebman_app
Database- MySQL:sql
USE webman_app; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
1
2
3
4
5
6
7 - PostgreSQL:sql
\c webman_app; -- Connect to newly created database CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
1
2
3
4
5
6
7
- MySQL:
Writing Web Project Code
Next, let's add code to define routes, create controllers, and implement logic to interact with both the database and cache.
Configure Routes
Edit the project's
config/route.php
file and add the following code to define the routes for our example:php<?php use Webman\Route; use app\controller\IndexController; use app\controller\CacheController; use app\controller\DatabaseController; // Define root path route, mapped to the index method of IndexController Route::any('/', [IndexController::class, 'index']); // Define routes for cache interaction Route::any('/memcached', [CacheController::class, 'memcached']); Route::any('/redis', [CacheController::class, 'redis']); // Define routes for database interaction Route::any('/mysql-add', [DatabaseController::class, 'mysqlAdd']); Route::any('/mysql', [DatabaseController::class, 'mysqlGet']); Route::any('/pgsql-add', [DatabaseController::class, 'pgsqlAdd']); Route::any('/pgsql', [DatabaseController::class, 'pgsqlGet']); // Add more routes here as needed...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21Create Controller Files
In the
app/controller
directory, createIndexController.php
,CacheController.php
, andDatabaseController.php
, and add the following code to each.app/controller/IndexController.php
: Handles requests to the root path.php<?php namespace app\controller; use support\Request; use support\Response; // Import Response class class IndexController { /** * Example method to handle requests to the root path * @param Request $request Current request object * @return Response Returns a Response object */ public function index(Request $request): Response // Explicit return type { // Return simple text response return response('Hello ServBay & Webman!'); // Updated welcome message } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20app/controller/CacheController.php
: Demonstrates using Memcached and Redis.php<?php namespace app\controller; use support\Request; use support\Response; use Memcached; // Import Memcached class use support\Redis; // Import Webman's Redis Facade class CacheController { /** * Demonstrate Memcached usage * @param Request $request * @return Response */ public function memcached(Request $request): Response { // Connect to Memcached. ServBay defaults to 127.0.0.1:11211 $memcached = new Memcached(); $memcached->addServer('127.0.0.1', 11211); // Set cache item, valid for 60 seconds $success = $memcached->set('servbay_key', 'Hello Memcached from ServBay!', 60); // Updated key and value if (!$success) { return response('Failed to set Memcached key', 500); } // Get cache item $value = $memcached->get('servbay_key'); // Updated key // Return retrieved value return response($value ?: 'Memcached key not found or expired'); // Added message for missing keys } /** * Demonstrate Redis usage * @param Request $request * @return Response */ public function redis(Request $request): Response { // Set cache item using Webman's Redis Facade Redis::set('servbay_redis_key', 'Hello Redis from ServBay!'); // Updated key and value // Get cache item using Webman's Redis Facade $value = Redis::get('servbay_redis_key'); // Updated key // Return retrieved value return response($value ?: 'Redis key not found'); // Added message for missing keys } }
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
52app/controller/DatabaseController.php
: Demonstrates MySQL and PostgreSQL operations.php<?php namespace app\controller; use support\Request; use support\Response; use support\Db; // Import Webman's Db Facade class DatabaseController { /** * Add a user to the MySQL database * @param Request $request * @return Response */ public function mysqlAdd(Request $request): Response { try { // Use Db Facade to connect to 'mysql' and insert data Db::connection('mysql')->table('users')->insert([ 'name' => 'ServBay Webman MySQL User', // Updated sample data 'email' => '[email protected]', // Updated example email 'created_at' => date('Y-m-d H:i:s') // Add created_at ]); return response('User added to MySQL'); // Updated response } catch (\Exception $e) { return response('Error adding user to MySQL: ' . $e->getMessage(), 500); // Error handling } } /** * Get user list from MySQL database * @param Request $request * @return Response */ public function mysqlGet(Request $request): Response { try { // Use Db Facade to connect to 'mysql' and get all users $users = Db::connection('mysql')->table('users')->get(); // Return user list in JSON format return response(json_encode($users), 200, ['Content-Type' => 'application/json']); // Explicit Content-Type } catch (\Exception $e) { return response('Error getting users from MySQL: ' . $e->getMessage(), 500); // Error handling } } /** * Add a user to the PostgreSQL database * @param Request $request * @return Response */ public function pgsqlAdd(Request $request): Response { try { // Use Db Facade to connect to 'pgsql' and insert data Db::connection('pgsql')->table('users')->insert([ 'name' => 'ServBay Webman PgSQL User', // Updated sample data 'email' => '[email protected]', // Updated example email 'created_at' => date('Y-m-d H:i:s') // Add created_at ]); return response('User added to PostgreSQL'); // Updated response } catch (\Exception $e) { return response('Error adding user to PostgreSQL: ' . $e->getMessage(), 500); // Error handling } } /** * Get user list from PostgreSQL database * @param Request $request * @return Response */ public function pgsqlGet(Request $request): Response { try { // Use Db Facade to connect to 'pgsql' and get all users $users = Db::connection('pgsql')->table('users')->get(); // Return user list in JSON format return response(json_encode($users), 200, ['Content-Type' => 'application/json']); // Explicit Content-Type } catch (\Exception $e) { return response('Error getting users from PostgreSQL: ' . $e->getMessage(), 500); // Error handling } } }
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
79
80
81
82
83
84
Configure Database Connections
Edit the project's
config/database.php
file to set up MySQL and PostgreSQL connection info. ServBay's default database host is127.0.0.1
, with ports3306
for MySQL and5432
for PostgreSQL. Theroot
user password ispassword
.php<?php /** * Database configuration */ return [ // Default database connection 'default' => 'mysql', // Database connection configurations 'connections' => [ 'mysql' => [ 'driver' => 'mysql', // ServBay's default MySQL host and port 'host' => '127.0.0.1', 'port' => 3306, // Database name created earlier 'database' => 'webman_app', // ServBay's default MySQL username 'username' => 'root', // ServBay's default MySQL password 'password' => 'password', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], 'pgsql' => [ 'driver' => 'pgsql', // ServBay's default PostgreSQL host and port 'host' => '127.0.0.1', 'port' => 5432, // Database name created earlier 'database' => 'webman_app', // ServBay's default PostgreSQL username 'username' => 'root', // ServBay's default PostgreSQL password 'password' => 'password', 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', 'sslmode' => 'prefer', // Or require, verify-ca, verify-full ], // Add additional database connections here as needed... ], ];
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
46Important: In production environments, always change the default database password, and avoid hardcoding sensitive information in code.
Running the Webman Project
Webman projects are typically started via the included start.php
script, which launches Workerman processes. Unlike the traditional Nginx/Apache + PHP-FPM setup, Webman is a resident memory asynchronous application.
In the project root (/Applications/ServBay/www/servbay-webman-app
), run the command below to start your Webman project:
php start.php start
You'll see startup information on the terminal. By default, Webman will listen for HTTP requests on 127.0.0.1:8787
.
- Note: The
php
command refers to the PHP executable from your ServBay environment. ServBay automatically configures your terminal environment, allowing you to use the installed PHP version directly. - To run Webman in the background, add the
-d
flag:php start.php start -d
. - To stop the Webman service, run:
php start.php stop
. - To restart the Webman service, run:
php start.php restart
. - For smooth restarts (without interrupting ongoing requests), use:
php start.php reload
.
Testing the Project
When Webman successfully starts and listens on 127.0.0.1:8787
, you can test individual features by visiting the URLs below in your browser:
http://localhost:8787/
- You'll see the page output:Hello ServBay & Webman!
http://localhost:8787/memcached
- You'll see the output:Hello Memcached from ServBay!
This confirms you've used Webman to connect and use ServBay's Memcached.http://localhost:8787/redis
- You'll see:Hello Redis from ServBay!
This confirms Redis is working via Webman and ServBay.http://localhost:8787/mysql-add
- You'll see:User added to MySQL
. This inserts a row in theusers
table of the MySQL database you created earlier.http://localhost:8787/mysql
- You'll see a JSON list of users from the MySQLusers
table.http://localhost:8787/pgsql-add
- You'll see:User added to PostgreSQL
. This adds a record in the PostgreSQLusers
table.http://localhost:8787/pgsql
- You'll see a JSON list of users from the PostgreSQLusers
table.
If you encounter issues accessing these URLs, check the Webman terminal output for error messages, and confirm that MySQL, PostgreSQL, Redis, and Memcached are running in ServBay, and that the necessary PHP extensions are enabled.
Frequently Asked Questions (FAQ)
- Q: 'php start.php start' command not found?
- A: Make sure you've
cd
'd into theservbay-webman-app
project directory in your terminal. Also, confirm that ServBay's PHP is in your system PATH (ServBay usually handles this automatically).
- A: Make sure you've
- Q: Visiting 'localhost:8787' returns a connection error?
- A: Check the output of
php start.php start
in your terminal for errors. Ensure port8787
isn't occupied by another process. If it is, change the listening port in Webman's config (e.g., editconfig/server.php
).
- A: Check the output of
- Q: Database connection failed?
- A: Make sure MySQL and PostgreSQL are running in ServBay. Double-check
config/database.php
connection info (host, port, database, username, password) matches ServBay's (default userroot
, passwordpassword
). Ensure thewebman_app
database andusers
table exist.
- A: Make sure MySQL and PostgreSQL are running in ServBay. Double-check
- Q: Memcached or Redis connection failed?
- A: Confirm Memcached and Redis are running in ServBay. Check that the connection addresses and ports (
127.0.0.1:11211
for Memcached,127.0.0.1:6379
for Redis) inapp/controller/CacheController.php
are correct. Make sure your PHP version has thememcached
andredis
extensions enabled.
- A: Confirm Memcached and Redis are running in ServBay. Check that the connection addresses and ports (
Summary
By following the steps above, you've successfully created, configured, and run a basic Webman project in the ServBay local development environment. You learned how to quickly set up a Webman development environment using ServBay's all-in-one toolkit and integrated database and caching features. The high performance of Webman, combined with the convenience of ServBay, provides you with powerful support for asynchronous PHP application development. We hope this guide helps you make the most of ServBay and Webman to build outstanding web applications.