The following column workerman usage tutorial will introduce to you the method of using Laravel5.3 and Workerman together (asynchronously). I hope it will be helpful to friends in need!

Looking at the information online, there are ready-made composer components that are combined with Workerman, but I personally feel that they are not reliable. There are too few stars on github, and it is difficult to adjust if there are problems. I just wanted to try it myself first.
My method requires a little bit of Workerman source code to modify, and it directly introduces Workerman's code files, which feels a bit low, but my talent is limited and I haven't thought of a better method for the time being.
Preparation:
1. You need to understand the use of the command line under the Laravel framework. Please refer to the Chinese version of the tutorial
2. You need to understand the basic knowledge of Workerman
Scenario: After the user registers, send an email reminder to the user asynchronously
1. Place the Workerman framework in the app directory
2. Create the command code:
php artisan make:command SendEmail
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Message;
use Workerman\Worker;
require app_path('Workerman/Workerman_Linux/Autoloader.php');
class SendEmail extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'send:email {action}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
*/
public function handle()
{
$mailWorker = new Worker('Text://0.0.0.0:12345');
$mailWorker->count = 4;
$mailWorker->name = 'MailWorker';
$mailWorker->onMessage = function ($connection, $emailData) {
$emailData = json_decode($emailData);
$name = $emailData->name;
$email = $emailData->to;
Mail::raw('注册成功', function (Message $message) use ($email) {
$message->to($email)->subject(trans('mail.welcome_register'));
});
// 写入日志
Log::useFiles(storage_path() . '/logs/event.log', 'info');
Log::info("{$name}({$email})注册成功");
};
Worker::runAll();
}
}and above It is the workerman server. Start it with the command line:
php artisan send:email start
At this time, an error will be reported on the command line: Workerman[artisan] not run. The reason is that Workerman will use the first parameter artisan to start the current file. In fact, send:email is the startup file we want
Solution: Modify Workerman’s parsing parameter code
Workerman\Workerman_Linux\Worker.php, modify the parseCommand method (just change the keys of $argv Just add 1):
/**
* Parse command.
* php yourfile.php start | stop | restart | reload | status
*
* @return void
*/
protected static function parseCommand()
{
global $argv;
if($argv[0] == 'artisan') // laravel框架下处理
{
// Check argv;
$start_file = $argv[1];
if (!isset($argv[2])) {
exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n");
}
// Get command.
$command = trim($argv[2]);
$command2 = isset($argv[3]) ? $argv[3] : '';
}
else
{
// Check argv;
$start_file = $argv[0];
if (!isset($argv[1])) {
exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n");
}
// Get command.
$command = trim($argv[1]);
$command2 = isset($argv[2]) ? $argv[2] : '';
}
// 只要略修改上面的参数解析部分即可
..........................
}Restart OK:
php artisan send:email start
3. The server is completed, the following is the client code
My email operation code is treated as an event logic, so write the code in the event listener file:
app\Listeners\SendMailEventListener.php:
<?php
namespace App\Listeners;
use App\Events\SendMailEvent;class SendMailEventListener extends BaseEventListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param SendMailEvent $event
* @return void
*/
public function handle($event)
{
// 发送邮件通知注册成功
if ($event->user->scene == 'do_register') {
$email = $event->user->email;
//$ip = "mail_worker 的ip" ,本机的话为127.0.0.1
$socket = @stream_socket_client('tcp://127.0.0.1:12345', $errno, $errmsg, 5);
if ($socket) {
$mail_data = ['name'=>$event->user->name,'to' => $email, 'content' => trans('mail.welcome_register')];
// 注意,Text协议后面"\n"换行符是必须的
$mail_buffer = json_encode($mail_data) . "\n";
// 发送给mail worker
fwrite($socket, $mail_buffer);
}
// $email = $event->user->email;
// Mail::raw('注册成功',function (Message $message) use ($email) {
// $message->to($email)->subject(trans('mail.welcome_register'));
// });
}
}
}4. Summary steps
Start the server---Register the user---Trigger the SendEmail event---socket client to the service Write data on the client---Send email on the server
Recommendation:Workerman Tutorial
The above is the detailed content of Laravel5.3 combined with Workerman (asynchronous). For more information, please follow other related articles on the PHP Chinese website!
What Are the Key Features of Workerman's Built-in WebSocket Client?Mar 18, 2025 pm 04:20 PMWorkerman's WebSocket client enhances real-time communication with features like asynchronous communication, high performance, scalability, and security, easily integrating with existing systems.
How to Use Workerman for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:15 PMThe article discusses using Workerman, a high-performance PHP server, to build real-time collaboration tools. It covers installation, server setup, real-time feature implementation, and integration with existing systems, emphasizing Workerman's key f
What Are the Best Ways to Optimize Workerman for Low-Latency Applications?Mar 18, 2025 pm 04:14 PMThe article discusses optimizing Workerman for low-latency applications, focusing on asynchronous programming, network configuration, resource management, data transfer minimization, load balancing, and regular updates.
How to Implement Real-Time Data Synchronization with Workerman and MySQL?Mar 18, 2025 pm 04:13 PMThe article discusses implementing real-time data synchronization using Workerman and MySQL, focusing on setup, best practices, ensuring data consistency, and addressing common challenges.
What Are the Key Considerations for Using Workerman in a Serverless Architecture?Mar 18, 2025 pm 04:12 PMThe article discusses integrating Workerman into serverless architectures, focusing on scalability, statelessness, cold starts, resource management, and integration complexity. Workerman enhances performance through high concurrency, reduced cold sta
How to Build a High-Performance E-Commerce Platform with Workerman?Mar 18, 2025 pm 04:11 PMThe article discusses building a high-performance e-commerce platform using Workerman, focusing on its features like WebSocket support and scalability to enhance real-time interactions and efficiency.
What Are the Advanced Features of Workerman's WebSocket Server?Mar 18, 2025 pm 04:08 PMWorkerman's WebSocket server enhances real-time communication with features like scalability, low latency, and security measures against common threats.
How to Use Workerman for Building Real-Time Analytics Dashboards?Mar 18, 2025 pm 04:07 PMThe article discusses using Workerman, a high-performance PHP server, to build real-time analytics dashboards. It covers installation, server setup, data processing, and frontend integration with frameworks like React, Vue.js, and Angular. Key featur


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools






