Home PHP Framework Workerman Laravel5.3 combined with Workerman (asynchronous)

Laravel5.3 combined with Workerman (asynchronous)

Nov 25, 2019 pm 05:11 PM
laravel workerman

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!

Laravel5.3 combined with Workerman (asynchronous)

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 == &#39;do_register&#39;) {
            $email = $event->user->email;

            //$ip = "mail_worker 的ip" ,本机的话为127.0.0.1
            $socket = @stream_socket_client(&#39;tcp://127.0.0.1:12345&#39;, $errno, $errmsg, 5);
            if ($socket) {
                $mail_data = [&#39;name&#39;=>$event->user->name,&#39;to&#39; => $email, &#39;content&#39; => trans(&#39;mail.welcome_register&#39;)];
                // 注意,Text协议后面"\n"换行符是必须的
                $mail_buffer = json_encode($mail_data) . "\n";
                // 发送给mail worker
                fwrite($socket, $mail_buffer);
            }

//            $email = $event->user->email;
//            Mail::raw(&#39;注册成功&#39;,function (Message $message) use ($email) {
//                $message->to($email)->subject(trans(&#39;mail.welcome_register&#39;));
//            });
        }
    }
}

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Peak: How To Revive Players
1 months ago By DDD
PEAK How to Emote
4 weeks ago By Jack chen

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with pivot tables in Laravel Many-to-Many relationships Working with pivot tables in Laravel Many-to-Many relationships Jul 07, 2025 am 01:06 AM

ToworkeffectivelywithpivottablesinLaravel,firstaccesspivotdatausingwithPivot()orwithTimestamps(),thenupdateentrieswithupdateExistingPivot(),managerelationshipsviadetach()andsync(),andusecustompivotmodelswhenneeded.1.UsewithPivot()toincludespecificcol

Adding multilingual support to a Laravel application Adding multilingual support to a Laravel application Jul 03, 2025 am 01:17 AM

The core methods for Laravel applications to implement multilingual support include: setting language files, dynamic language switching, translation URL routing, and managing translation keys in Blade templates. First, organize the strings of each language in the corresponding folders (such as en, es, fr) in the /resources/lang directory, and define the translation content by returning the associative array; 2. Translate the key value through the \_\_() helper function call, and use App::setLocale() to combine session or routing parameters to realize language switching; 3. For translation URLs, paths can be defined for different languages ​​through prefixed routing groups, or route alias in language files dynamically mapped; 4. Keep the translation keys concise and

Sending different types of notifications with Laravel Sending different types of notifications with Laravel Jul 06, 2025 am 12:52 AM

Laravelprovidesacleanandflexiblewaytosendnotificationsviamultiplechannelslikeemail,SMS,in-appalerts,andpushnotifications.Youdefinenotificationchannelsinthevia()methodofanotificationclass,andimplementspecificmethodsliketoMail(),toDatabase(),ortoVonage

Laravel MVC: real code samples Laravel MVC: real code samples Jul 03, 2025 am 12:35 AM

Laravel's MVC architecture consists of a model, a view and a controller, which are responsible for data logic, user interface and request processing respectively. 1) Create a User model to define data structures and relationships. 2) UserController processes user requests, including listing, displaying and creating users. 3) The view uses the Blade template to display user data. This architecture improves code clarity and maintainability.

Understanding and creating custom Service Providers in Laravel Understanding and creating custom Service Providers in Laravel Jul 03, 2025 am 01:35 AM

ServiceProvider is the core mechanism used in the Laravel framework for registering services and initializing logic. You can create a custom ServiceProvider through the Artisan command; 1. The register method is used to bind services, register singletons, set aliases, etc., and other services that have not yet been loaded cannot be called; 2. The boot method runs after all services are registered and is used to register event listeners, view synthesizers, middleware and other logic that depends on other services; common uses include binding interfaces and implementations, registering Facades, loading configurations, registering command-line instructions and view components; it is recommended to centralize relevant bindings to a ServiceProvider to manage, and pay attention to registration

Handling exceptions and logging errors in a Laravel application Handling exceptions and logging errors in a Laravel application Jul 02, 2025 pm 03:24 PM

The core methods for handling exceptions and recording errors in Laravel applications include: 1. Use the App\Exceptions\Handler class to centrally manage unhandled exceptions, and record or notify exception information through the report() method, such as sending Slack notifications; 2. Use Monolog to configure the log system, set the log level and output method in config/logging.php, and enable error and above level logs in production environment. At the same time, detailed exception information can be manually recorded in report() in combination with the context; 3. Customize the render() method to return a unified JSON format error response, improving the collaboration efficiency of the front and back end of the API. These steps are

Configuring and sending email notifications in Laravel Configuring and sending email notifications in Laravel Jul 05, 2025 am 01:26 AM

TosetupemailnotificationsinLaravel,firstconfiguremailsettingsinthe.envfilewithSMTPorservice-specificdetailslikeMAIL\_MAILER,MAIL\_HOST,MAIL\_PORT,MAIL\_USERNAME,MAIL\_PASSWORD,andMAIL\_FROM\_ADDRESS.Next,testtheconfigurationusingMail::raw()tosendasam

Managing database state for testing in Laravel Managing database state for testing in Laravel Jul 13, 2025 am 03:08 AM

Methods to manage database state in Laravel tests include using RefreshDatabase, selective seeding of data, careful use of transactions, and manual cleaning if necessary. 1. Use RefreshDatabasetrait to automatically migrate the database structure to ensure that each test is based on a clean database; 2. Use specific seeds to fill the necessary data and generate dynamic data in combination with the model factory; 3. Use DatabaseTransactionstrait to roll back the test changes, but pay attention to its limitations; 4. Manually truncate the table or reseed the database when it cannot be automatically cleaned. These methods are flexibly selected according to the type of test and environment to ensure the reliability and efficiency of the test.

See all articles