Using Swoole to Create High-Performance PHP Applications
What is Swoole?
Swoole is a high-performance networking framework for PHP that provides asynchronous, multithreading, and coroutine features, enabling PHP to handle high concurrency tasks like Node.js. It supports various protocols such as TCP, UDP, UnixSocket, HTTP, and WebSocket, making it suitable for building high-performance web servers, microservice architectures, real-time communication systems, etc.
Key Features and Advantages of Swoole
- High Performance: Written in C, Swoole offers extremely high performance and supports asynchronous IO and coroutines, capable of handling high concurrency requests.
- Rich Features: Supports various network protocols, timers, process management, memory management, and more to meet diverse development needs.
- Ease of Use: Provides easy-to-use APIs and comprehensive documentation to help developers get started quickly.
- Strong Extensibility: Supports custom extensions and plugins, allowing flexible customization as needed.
Swoole is an ideal choice for building high-performance web applications and real-time communication systems, suitable for projects ranging from small applications to large enterprise-level systems.
Installation of Swoole
In this article, we will introduce how to install and use Swoole in a ServBay environment.
TIP
ServBay recommends developers place their websites in the /Applications/ServBay/www
directory for easy management.
Step 1: Install Swoole Extension
Enable Swoole Extension
ServBay has the Swoole extension built-in. Users need to enable it and restart PHP. Please refer to the article How to enable the built-in Swoole module in ServBay to enable the Swoole module.
Step 2: Create Project Directory
Create the project directory and navigate into it:
cd /Applications/ServBay/www
mkdir servbay-swoole-app
cd servbay-swoole-app
2
3
Step 3: Create Swoole Server Script
Create a server.php
file in the project directory and write a simple Swoole HTTP server:
<?php
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
$server = new Server("0.0.0.0", 9501);
$server->on("start", function (Server $server) {
echo "Swoole HTTP server is started at http://0.0.0.0:9501\n";
});
$server->on("request", function (Request $request, Response $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello ServBay!");
});
$server->start();
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Step 4: Run Swoole Server
Run the following command in the terminal to start the Swoole server:
php server.php
You will see the following output:
Swoole HTTP server is started at http://0.0.0.0:9501
Step 5: Access Swoole Server
Open your browser and visit http://localhost:9501
, you will see the page output Hello ServBay!
.
Building Web Applications with Swoole
In this section, we will introduce how to use Swoole to build a simple web application.
Create Controllers and Routes
Create an app
directory in the project directory, and within it, create controllers
and routes
directories:
mkdir -p app/controllers
mkdir -p app/routes
2
Create a HomeController.php
file in the app/controllers
directory:
<?php
namespace App\Controllers;
class HomeController
{
public function index()
{
return "Welcome to ServBay!";
}
public function hello($name)
{
return "Hello, $name!";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Create a web.php
file in the app/routes
directory:
<?php
use App\Controllers\HomeController;
return [
'GET /' => [HomeController::class, 'index'],
'GET /hello/{name}' => [HomeController::class, 'hello'],
];
2
3
4
5
6
7
8
Update Swoole Server Script
Update the server.php
file to add route resolution and controller invocation logic:
<?php
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
use FastRoute\RouteCollector;
use function FastRoute\simpleDispatcher;
require 'vendor/autoload.php';
$server = new Server("0.0.0.0", 9501);
$routes = require __DIR__ . '/app/routes/web.php';
$dispatcher = simpleDispatcher(function (RouteCollector $r) use ($routes) {
foreach ($routes as $route => $handler) {
list($method, $path) = explode(' ', $route);
$r->addRoute($method, $path, $handler);
}
});
$server->on("start", function (Server $server) {
echo "Swoole HTTP server is started at http://0.0.0.0:9501\n";
});
$server->on("request", function (Request $request, Response $response) use ($dispatcher) {
$routeInfo = $dispatcher->dispatch($request->server['request_method'], $request->server['request_uri']);
switch ($routeInfo[0]) {
case \FastRoute\Dispatcher::NOT_FOUND:
$response->status(404);
$response->end('404 Not Found');
break;
case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
$response->status(405);
$response->end('405 Method Not Allowed');
break;
case \FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
list($class, $method) = $handler;
$response->header("Content-Type", "text/plain");
$response->end(call_user_func_array([new $class, $method], $vars));
break;
}
});
$server->start();
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
Install FastRoute
Run the following command in the project root directory to install the FastRoute routing library:
composer require nikic/fast-route
Run Swoole Server
Run the following command in the terminal to start the Swoole server:
php server.php
Access Web Application
Open your browser and visit the following URLs:
http://localhost:9501/
: You will see the page outputWelcome to ServBay!
.http://localhost:9501/hello/ServBay
: You will see the page outputHello, ServBay!
.
Handling WebSocket Connections with Swoole
Swoole also supports the WebSocket protocol, which can be used to build real-time communication applications. We will introduce how to use Swoole to handle WebSocket connections.
Create WebSocket Server Script
Create a websocket_server.php
file in the project directory and write a simple WebSocket server:
<?php
use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
$server = new Server("0.0.0.0", 9502);
$server->on("start", function (Server $server) {
echo "Swoole WebSocket server is started at ws://0.0.0.0:9502\n";
});
$server->on("open", function (Server $server, Request $request) {
echo "connection open: {$request->fd}\n";
});
$server->on("message", function (Server $server, Frame $frame) {
echo "received message: {$frame->data}\n";
$server->push($frame->fd, "Hello, {$frame->data}");
});
$server->on("close", function ($ser, $fd) {
echo "connection close: {$fd}\n";
});
$server->start();
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
Run WebSocket Server
Run the following command in the terminal to start the WebSocket server:
php websocket_server.php
You will see the following output:
Swoole WebSocket server is started at ws://0.0.0.0:9502
Connect to WebSocket Server
You can use a WebSocket client in your browser or other WebSocket client tools (such as wscat
) to connect to the WebSocket server.
Connect Using wscat
Install
wscat
:bashnpm install -g wscat
1Connect to the WebSocket server:
bashwscat -c ws://localhost:9502
1Send a message:
bash> Hello ServBay
1
You will see the server's response:
< Hello, Hello ServBay
By following the above steps, you successfully created and ran a Swoole project and used Swoole's features to handle HTTP requests and WebSocket connections. Swoole's high performance and rich features make it an ideal choice for building high-concurrency applications.