This article will give you relevant knowledge about Laravel and Swoole. The main content is to teach you how to change Laravel to the Swoole version (try to learn, it is not recommended to change the existing project). Let’s take a look together. I hope it will be helpful to everyone. Helped!
Preface
It is not recommended to use in production environment
Create a new laravel project
laravel new swoole-laravel
Change Laravel to Swoole version
Create a swoole_server.php file in the root directory of Laravel, and then copy the code in public/index.php over [Recommended learning: laravel video tutorial 】
<?php use Illuminate\Contracts\Http\Kernel; use Illuminate\Http\Request; define('LARAVEL_START', microtime(true)); require __DIR__.'/../vendor/autoload.php'; $app = require_once __DIR__.'/../bootstrap/app.php'; $kernel = $app->make(Kernel::class); $response = $kernel->handle( $request = Request::capture() )->send(); $kernel->terminate($request, $response);
In the first step, the loading of the framework file is certain, and it should be loaded in the main process. There is no need for sub-processes or coroutines to load it repeatedly. Therefore, the require above does not need to be touched.
The second step is to start an HTTP Swoole service. This has been mentioned many times before. Note that in onRequest, we should put the $kernel related code in it.
$http = new Swoole\Http\Server('0.0.0.0', 9501); $http->on('Request', function ($req, $res) use($app) { try { $kernel = $app->make(Kernel::class); $response = $kernel->handle( $request = Request::capture() )->send(); $kernel->terminate($request, $response); }catch(\Exception $e){ print_r($e->getMessage()); } }); echo "服务启动", PHP_EOL; $http->start();
Is this enough? Why don't you give it a try first. Under normal circumstances, you may not be able to obtain any input or output. Why is this?
The third step is to solve the input problem. In fact, super global variables do not work in Swoole, so variables such as $_GET will become invalid, and Request-related objects in Laravel will not be able to obtain data. What to do about this? We just get this data from the parameters of onRequest and then put it back into $_GET in the current process coroutine.
$http->on('Request', function ($req, $res) use($app) { $_SERVER = []; if(isset($req->server)){ foreach($req->server as $k => $v){ $_SERVER[strtoupper($k)] = $v; } } $_GET = []; if(isset($req->get)){ foreach ($req->get as $k => $v){ $_GET[$k] = $v; } } $_POST = []; if(isset($req->post)){ foreach ($req->post as $k => $v){ $_POST[$k] = $v; } } try { $kernel = $app->make(Kernel::class); $response = $kernel->handle( $request = Request::capture() )->send(); $kernel->terminate($request, $response); }catch(\Exception $e){ print_r($e->getMessage()); } });
The above three pieces of code solve the problems of $_SERVER, $_GET and $_POST respectively. Now if you try again, the parameters can be received, but why is the output printed on the console?
The fourth step is to solve the output problem, put all the output in the frame into the output buffer, and then use Swoole's Response to return.
$http->on('Request', function ($req, $res) use($app) { $_SERVER = []; if(isset($req->server)){ foreach($req->server as $k => $v){ $_SERVER[strtoupper($k)] = $v; } } $_GET = []; if(isset($req->get)){ foreach ($req->get as $k => $v){ $_GET[$k] = $v; } } $_POST = []; if(isset($req->post)){ foreach ($req->post as $k => $v){ $_POST[$k] = $v; } } //把返回放到一个缓冲区里 ob_start(); try { $kernel = $app->make(Kernel::class); $response = $kernel->handle( $request = Request::capture() )->send(); $kernel->terminate($request, $response); }catch(\Exception $e){ print_r($e->getMessage()); } $ob = ob_get_contents(); ob_end_clean(); $res->end($ob); });
The last ob_start () content is also what we have studied before, so we won’t explain it further.
All code
start();
At this point, our simplest framework transformation is completed, let’s try the effect quickly.
Run
php swoole_server.php
Access
http://47.113.xxx.xx:9501/
Try the coroutine effect
First define a route. Or we can directly modify the default route.
Route::get('/', function () { echo Swoole\Coroutine::getCid(), "<br/>"; print_r(Swoole\Coroutine::stats()); Swoole\Coroutine::sleep(10); echo "<br/>"; echo getmypid(), "<br/>"; // return view('welcome'); });
Printed a bunch of things, but they should all be familiar. The first two are the output of coroutine ID and coroutine information, and then we Swoole\Coroutine::sleep () for 10 seconds, and then print Here is the process ID.
Then we open the browser and prepare to access the two tabs together.
// 第一个访问的页面 1 Array ( [event_num] => 2 [signal_listener_num] => 0 [aio_task_num] => 0 [aio_worker_num] => 0 [aio_queue_size] => 0 [c_stack_size] => 2097152 [coroutine_num] => 1 [coroutine_peak_num] => 1 [coroutine_last_cid] => 1 ) 1468 // 第二个访问的页面 2 Array ( [event_num] => 2 [signal_listener_num] => 0 [aio_task_num] => 0 [aio_worker_num] => 0 [aio_queue_size] => 0 [c_stack_size] => 2097152 [coroutine_num] => 2 [coroutine_peak_num] => 2 [coroutine_last_cid] => 2 ) 1468
Do you see it? Each onRequest event actually opens a new coroutine to handle the request, so their coroutine IDs are different. At the same time, the second request will not wait until 20 seconds to return because the first request is blocked. Finally, in the coroutine status, we also see that there are two coroutine_nums displayed in the second request, indicating that there are currently two coroutines processing tasks. In the end, the processes are the same, they all follow the same process.
Try the multi-process effect
By default, the above code is a main process and a Worker process, and then uses the coroutine capability. In fact, this effect can instantly kill the ordinary PHP-FPM effect. But we need to make full use of the performance of multi-core machines, that is to say, we enable multi-processes and use the super-powerful processing mode of multi-processes and multi-coroutines. The simplest way is to directly set the number of process workers for the HTTP service.
$http->set(array( 'worker_num' => 4, // 'worker_num' => 1,单进程 ));
Now run the server and you can see several more processes. Then we create a new test route
Route::get('/a', function () { echo Swoole\Coroutine::getCid(), "<br/>"; print_r(Swoole\Coroutine::stats()); echo "<br/>"; echo getmypid(), "<br/>"; });
Now visit the homepage and this /a page again.
// 首页一 1 Array ( [event_num] => 2 [signal_listener_num] => 0 [aio_task_num] => 0 [aio_worker_num] => 0 [aio_queue_size] => 0 [c_stack_size] => 2097152 [coroutine_num] => 1 [coroutine_peak_num] => 1 [coroutine_last_cid] => 1 ) 1562 // 首页二 1 Array ( [event_num] => 2 [signal_listener_num] => 0 [aio_task_num] => 0 [aio_worker_num] => 0 [aio_queue_size] => 0 [c_stack_size] => 2097152 [coroutine_num] => 1 [coroutine_peak_num] => 1 [coroutine_last_cid] => 1 ) 1563 // /a 页面 1 Array ( [event_num] => 2 [signal_listener_num] => 0 [aio_task_num] => 0 [aio_worker_num] => 0 [aio_queue_size] => 0 [c_stack_size] => 2097152 [coroutine_num] => 1 [coroutine_peak_num] => 1 [coroutine_last_cid] => 1 ) 1564
I found no, and their process IDs are all different. If there is no blocking, the process will be switched first. If all processes are blocked, the coroutine will be created in a loop for in-process processing.
The above is the detailed content of Try how to change Laravel to Swoole version. For more information, please follow other related articles on the PHP Chinese website!

Laravel is suitable for building web applications quickly, while Python is suitable for a wider range of application scenarios. 1.Laravel provides EloquentORM, Blade template engine and Artisan tools to simplify web development. 2. Python is known for its dynamic types, rich standard library and third-party ecosystem, and is suitable for Web development, data science and other fields.

Laravel and Python each have their own advantages: Laravel is suitable for quickly building feature-rich web applications, and Python performs well in the fields of data science and general programming. 1.Laravel provides EloquentORM and Blade template engines, suitable for building modern web applications. 2. Python has a rich standard library and third-party library, and Django and Flask frameworks meet different development needs.

Laravel is worth choosing because it can make the code structure clear and the development process more artistic. 1) Laravel is based on PHP, follows the MVC architecture, and simplifies web development. 2) Its core functions such as EloquentORM, Artisan tools and Blade templates enhance the elegance and robustness of development. 3) Through routing, controllers, models and views, developers can efficiently build applications. 4) Advanced functions such as queue and event monitoring further improve application performance.

Laravel is not only a back-end framework, but also a complete web development solution. It provides powerful back-end functions, such as routing, database operations, user authentication, etc., and supports front-end development, improving the development efficiency of the entire web application.

Laravel is suitable for web development, Python is suitable for data science and rapid prototyping. 1.Laravel is based on PHP and provides elegant syntax and rich functions, such as EloquentORM. 2. Python is known for its simplicity, widely used in Web development and data science, and has a rich library ecosystem.

Laravelcanbeeffectivelyusedinreal-worldapplicationsforbuildingscalablewebsolutions.1)ItsimplifiesCRUDoperationsinRESTfulAPIsusingEloquentORM.2)Laravel'secosystem,includingtoolslikeNova,enhancesdevelopment.3)Itaddressesperformancewithcachingsystems,en

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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

Zend Studio 13.0.1
Powerful PHP integrated development environment