laravel-swoole
High performance HTTP server based on Swoole. Speed up your Laravel or Lumen applications.
Top Related Projects
The Laravel Lumen Framework.
Supercharge your Laravel application's performance.
🤯 High-performance PHP application server, process manager written in Go and powered with plugins
🚀 A coroutine framework that focuses on hyperspeed and flexibility. Building microservice or middleware with ease.
A non-blocking concurrency framework for PHP applications. 🐘
Provides a structured process for converting a Request into a Response
Quick Overview
The swooletw/laravel-swoole
project is a Laravel package that integrates the Swoole HTTP server into the Laravel framework, providing a high-performance, asynchronous, and scalable web application solution.
Pros
- High Performance: Swoole is a high-performance, asynchronous, and concurrent PHP network framework that can significantly improve the performance of Laravel applications.
- Asynchronous Processing: Swoole's asynchronous architecture allows for efficient handling of concurrent requests, leading to improved response times and better resource utilization.
- Scalability: The Swoole-based server can handle a large number of concurrent connections, making it suitable for building scalable web applications.
- Seamless Integration: The
swooletw/laravel-swoole
package provides a seamless integration between Swoole and the Laravel framework, allowing developers to leverage Swoole's capabilities without significant changes to their existing codebase.
Cons
- Learning Curve: Developers who are new to Swoole may face a learning curve in understanding its asynchronous programming model and how it differs from the traditional, synchronous PHP execution model.
- Compatibility: The package may not be compatible with all Laravel packages or features, and developers may need to carefully evaluate their application's dependencies before adopting it.
- Deployment Complexity: Deploying a Swoole-based application may require additional configuration and setup compared to a traditional Laravel deployment, which could be a barrier for some developers.
- Limited Documentation: The project's documentation, while generally good, may not cover all the edge cases or advanced use cases that developers might encounter.
Code Examples
Here are a few code examples demonstrating the usage of the swooletw/laravel-swoole
package:
- Configuring the Swoole Server:
// config/swoole_http.php
return [
'server' => [
'host' => env('SWOOLE_HTTP_HOST', '0.0.0.0'),
'port' => env('SWOOLE_HTTP_PORT', '1215'),
'options' => [
'worker_num' => env('SWOOLE_HTTP_WORKER_NUM', 4),
'task_worker_num' => env('SWOOLE_HTTP_TASK_WORKER_NUM', 4),
],
],
];
- Registering the Swoole Service Provider:
// config/app.php
'providers' => [
// ...
SwooleTW\Http\LaravelServiceProvider::class,
],
- Handling Requests with Swoole:
// app/Http/Controllers/ExampleController.php
class ExampleController extends Controller
{
public function index()
{
return view('example');
}
public function asyncTask()
{
$this->dispatch(new AsyncTask());
return response()->json(['message' => 'Task dispatched']);
}
}
- Dispatching Asynchronous Tasks:
// app/Jobs/AsyncTask.php
class AsyncTask implements ShouldQueue
{
public function handle()
{
// Perform some time-consuming task asynchronously
sleep(5);
// ...
}
}
Getting Started
To get started with the swooletw/laravel-swoole
package, follow these steps:
- Install the package using Composer:
composer require swooletw/laravel-swoole
- Publish the configuration file:
php artisan vendor:publish --provider="SwooleTW\Http\LaravelServiceProvider"
-
Configure the Swoole server settings in the
config/swoole_http.php
file. -
Register the Swoole service provider in your
config/app.php
file:
'providers' => [
// ...
SwooleTW\Http\LaravelServiceProvider::class,
],
- Start the Swoole server:
php artisan swoole:http start
- Visit your application in the browser to see the Swoole-powered Laravel application in
Competitor Comparisons
The Laravel Lumen Framework.
Pros of Lumen
- Lumen is a lightweight and fast micro-framework, making it suitable for building RESTful APIs and microservices.
- Lumen has a smaller footprint and requires fewer resources compared to the full Laravel framework.
- Lumen provides a streamlined approach to application development, focusing on the essentials and reducing complexity.
Cons of Lumen
- Lumen has a smaller ecosystem and community compared to the full Laravel framework, which may limit the availability of third-party packages and resources.
- Lumen has a more limited feature set compared to Laravel, which may not be suitable for more complex web applications.
- Migrating from Lumen to the full Laravel framework may require more effort due to the differences in their architectures.
Code Comparison
Laravel-Swoole
$app = new Swoole\Http\Server("0.0.0.0", 9501);
$app->on("start", function ($server) {
echo "Swoole HTTP server is started at http://0.0.0.0:9501\n";
});
$app->on("request", function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello, Swoole.\n");
});
$app->start();
Lumen
$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../')
);
$app->get('/', function () use ($app) {
return $app->version();
});
$app->run();
Supercharge your Laravel application's performance.
Pros of Laravel Octane
- Octane is officially maintained by the Laravel team, ensuring compatibility and support.
- Octane provides a more streamlined and opinionated approach to running Laravel applications in a high-performance environment.
- Octane integrates with popular PHP servers like Roadrunner and Swoole, allowing for easy setup and configuration.
Cons of Laravel Octane
- Octane may have a steeper learning curve compared to Laravel-Swoole, as it introduces new concepts and requires a different setup.
- Octane's opinionated nature may limit flexibility for developers who prefer more control over the underlying server configuration.
- Octane's performance benefits may be more noticeable in larger, more complex applications, while smaller projects may not see as significant of an improvement.
Code Comparison
Laravel Octane:
use Illuminate\Http\Request;
use Laravel\Octane\Contracts\OperationTerminated;
use Laravel\Octane\Contracts\ResetsRequestState;
use Laravel\Octane\Contracts\SupportsPooling;
class MyController extends Controller implements SupportsPooling, ResetsRequestState
{
public function __invoke(Request $request)
{
// ...
}
public function terminate(OperationTerminated $event)
{
// ...
}
public function reset()
{
// ...
}
}
Laravel-Swoole:
use Swoole\Http\Request as SwooleRequest;
use Swoole\Http\Response as SwooleResponse;
class MyController extends Controller
{
public function __invoke(SwooleRequest $request, SwooleResponse $response)
{
// ...
}
}
🤯 High-performance PHP application server, process manager written in Go and powered with plugins
Pros of RoadRunner
- RoadRunner is a high-performance PHP application server that can handle a large number of concurrent connections, making it a suitable choice for high-traffic web applications.
- RoadRunner provides a modular architecture, allowing developers to easily integrate custom plugins and extend its functionality.
- RoadRunner supports a wide range of PHP frameworks, including Laravel, Symfony, and Zend, making it a versatile choice for various PHP projects.
Cons of RoadRunner
- RoadRunner may have a steeper learning curve compared to Laravel Swoole, as it requires a deeper understanding of the underlying server architecture.
- The RoadRunner ecosystem may not be as mature and well-documented as the Laravel Swoole ecosystem, which could make it more challenging for developers to find resources and support.
Code Comparison
Laravel Swoole
$server = new Server([
'host' => env('SWOOLE_HOST', '0.0.0.0'),
'port' => env('SWOOLE_PORT', 1215),
'options' => [
'worker_num' => env('SWOOLE_WORKERS', 4),
'task_worker_num' => env('SWOOLE_TASKS', 4),
],
]);
$server->on('request', function ($request, $response) {
$response->header('Content-Type', 'text/plain');
$response->end('Hello, Swoole!');
});
$server->start();
RoadRunner
$rr := roadrunner.NewServer(
&roadrunner.ServerConfig{
Command: "php worker.php",
Relay: "pipes",
Pool: &roadrunner.Config{
NumWorkers: int64(runtime.NumCPU()),
AllocateTimeout: time.Second * 10,
DestroyTimeout: time.Second * 60,
},
},
)
if err := rr.Serve(); err != nil {
log.Fatalln(err)
}
🚀 A coroutine framework that focuses on hyperspeed and flexibility. Building microservice or middleware with ease.
Pros of Hyperf
- Hyperf provides a more comprehensive set of features and components out of the box, including support for database, caching, middleware, and more.
- Hyperf has a more active community and a larger ecosystem of third-party packages and integrations.
- Hyperf is designed to be more scalable and performant, with support for distributed and microservices architectures.
Cons of Hyperf
- Hyperf has a steeper learning curve compared to Laravel Swoole, as it requires understanding of Hyperf's own conventions and architecture.
- Hyperf may be overkill for smaller projects or simple use cases, where Laravel Swoole might be a more lightweight and easier-to-use option.
- Hyperf's documentation, while comprehensive, can be less beginner-friendly compared to Laravel Swoole's documentation.
Code Comparison
Laravel Swoole:
$server = new Server();
$server->handle(function (Request $request, Response $response) {
$response->setContent('Hello, World!');
return $response;
});
$server->start();
Hyperf:
<?php
namespace App\Controller;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Utils\Codec\Json;
class IndexController
{
public function index(RequestInterface $request, ResponseInterface $response)
{
return $response->json(['message' => 'Hello, World!']);
}
}
A non-blocking concurrency framework for PHP applications. 🐘
Pros of Amp
- Amp is a low-level, event-driven, non-blocking I/O library for PHP, making it highly scalable and efficient.
- Amp provides a consistent and well-documented API, making it easier to work with compared to the more complex Laravel Swoole.
- Amp has a larger community and more active development, with more contributors and a wider range of supported features.
Cons of Amp
- Amp is a standalone library, while Laravel Swoole is specifically designed to integrate with the Laravel framework, which may be more convenient for Laravel developers.
- Amp has a steeper learning curve compared to Laravel Swoole, as it requires a deeper understanding of event-driven programming and non-blocking I/O.
- Amp may have fewer pre-built integrations and tools compared to the Laravel-specific ecosystem of Laravel Swoole.
Code Comparison
Amp:
$loop = Amp\Loop::get();
$server = Amp\Socket\Server::listen('0.0.0.0:8000');
$server->accept(function (Amp\Socket\Server $server, Amp\Socket\Client $client) use ($loop) {
$client->write("Hello, world!\n");
$client->end();
});
$loop->run();
Laravel Swoole:
$app = new Illuminate\Foundation\Application(
realpath(__DIR__ . '/../')
);
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
Provides a structured process for converting a Request into a Response
Pros of Symfony HTTP Kernel
- The Symfony HTTP Kernel is a mature and well-documented component, providing a robust foundation for building web applications.
- It offers a flexible and extensible architecture, allowing developers to customize and extend its functionality as needed.
- The Symfony HTTP Kernel is part of the larger Symfony framework, which benefits from a large and active community, providing a wealth of resources and support.
Cons of Symfony HTTP Kernel
- The Symfony HTTP Kernel may have a steeper learning curve compared to the Laravel-Swoole package, especially for developers who are more familiar with the Laravel ecosystem.
- The Symfony HTTP Kernel is a standalone component, which means that it may require more setup and configuration to integrate into a project, compared to the Laravel-Swoole package which is designed to work seamlessly with the Laravel framework.
Code Comparison
Symfony HTTP Kernel (simplified):
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
$this->boot();
try {
return $this->handleRaw($request, $type);
} catch (\Exception $e) {
if ($catch) {
return $this->handleException($e, $request, $type);
}
throw $e;
}
}
Laravel-Swoole:
public function handle($request)
{
$this->app->instance('request', $request);
$response = $this->app->dispatch($request);
return $response;
}
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Warning
This package is no longer maintained, we strongly recommend using Laravel's official laravel/octane as an alternative.
If you need coroutine support, consider trying laravel-hyperf for higher performance (This is a Laravel style Hyperf framework.)
Laravel-Swoole
This package provides a high performance HTTP server to speed up your Laravel/Lumen application based on Swoole.
Version Compatibility
PHP | Laravel | Lumen | Swoole |
---|---|---|---|
>=7.2 | >=5.5 | >=5.5 | >=4.3.1 |
Features
- Run Laravel/Lumen application on top of Swoole.
- Outstanding performance boosting up to 5x faster.
- Sandbox mode to isolate app container.
- Support running websocket server in Laravel.
- Support
Socket.io
protocol. - Support Swoole table for cross-process data sharing.
Documentation
Please see Wiki
Benchmark
Test with clean Lumen 5.6, using DigitalOcean 3 CPUs / 1 GB Memory / PHP 7.2 / Ubuntu 16.04.4 x64
Benchmarking Tool: wrk
wrk -t4 -c100 http://your.app
Nginx with FPM
wrk -t4 -c10 http://lumen-swoole.local
Running 10s test @ http://lumen-swoole.local
4 threads and 10 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 6.41ms 1.56ms 19.71ms 71.32%
Req/Sec 312.99 28.71 373.00 72.00%
12469 requests in 10.01s, 3.14MB read
Requests/sec: 1245.79
Transfer/sec: 321.12KB
Swoole HTTP Server
wrk -t4 -c10 http://lumen-swoole.local:1215
Running 10s test @ http://lumen-swoole.local:1215
4 threads and 10 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 2.39ms 4.88ms 105.21ms 94.55%
Req/Sec 1.26k 197.13 1.85k 68.75%
50248 requests in 10.02s, 10.88MB read
Requests/sec: 5016.94
Transfer/sec: 1.09MB
Q&A
The common questions are collected in Q&A. You can go check if your question is listed in the document.
Issues and Support
Please read Issues Guideline before you submit an issue, thanks.
Bugs and feature request are tracked on GitHub.
Credits
Alternatives
License
The Laravel-Swoole package is open-sourced software licensed under the MIT license.
Support on Beerpay
Hey dude! Help me out for a couple of :beers:!
Top Related Projects
The Laravel Lumen Framework.
Supercharge your Laravel application's performance.
🤯 High-performance PHP application server, process manager written in Go and powered with plugins
🚀 A coroutine framework that focuses on hyperspeed and flexibility. Building microservice or middleware with ease.
A non-blocking concurrency framework for PHP applications. 🐘
Provides a structured process for converting a Request into a Response
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot