swoole-by-examples icon indicating copy to clipboard operation
swoole-by-examples copied to clipboard

How to use it in Controller

Open amrishkakadiya opened this issue 1 year ago • 3 comments

Hello, When I am using following code block in my laravel application controller it is throwing error.

<?php
 
 namespace App\Http\Controllers\Api;
 
 use App\Http\Controllers\Controller;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Artisan;
 use Swoole\Coroutine;
 
 use function Swoole\Coroutine\go;
 use function Swoole\Coroutine\run;
 
 class TestingController extends Controller
 {
     public function index(Request $request)
     {
         run(function () {
             for ($i = 0; $i < 2_000; $i++) {
                 go(function () {
                     // Note that we use the PHP function sleep() directly.
                     sleep(1);
                 });
             }
 
             // Note that there are 2_001 coroutines created, including the main coroutine created by function call run().
             echo count(Coroutine::listCoroutines()), " active coroutines when reaching the end of the PHP script.\n";
         });
 
         return response()->json([
             'message' => 'Api Working As Expected ' . $request->type,
             'ismobile' => isMobileRequest()
         ]);
     }
 }

And the error is like image

Anyone can guide me how to use this code block inside Controller

amrishkakadiya avatar Oct 01 '22 10:10 amrishkakadiya

The issue was not caused by the code block added. If you use Laravel Octane, maybe there is some installation/configuration issue with Laravel Octane. Better follow the installation instructions of Laravel Octane and double check if anything is missing.

Also, make sure your controller does work before adding the coding block.

Besides that, if you use Laravel Octane, the code block won't work as expected because of two reasons:

  1. The \Swoole\Coroutine\run() function should not be used here. The\Swoole\Server class (shipped in Octane) already has it taken care of.
  2. By default, Laravel Octane has coroutine support disabled. Thus, inside the code block, please use \Swoole\Coroutine::sleep() instead of \sleep() (or enable coroutine support manually); otherwise, it takes 2,000 seconds to complete the HTTP request.

deminy avatar Oct 02 '22 05:10 deminy

Thanks @deminy for prompt reply.

  • Controller is working fine without that code block
  • Laravel octane is not installed in this project and not going to use it.
  • I will check with given sleep() method but cannot use Octane,

amrishkakadiya avatar Oct 02 '22 09:10 amrishkakadiya

I should have asked this question first: How did you run the Laravel application? Under PHP-FPM?

Swoole doesn't work under PHP-FPM. To run a Laravel application under Swoole, people have to use Octane or a Laravel adapter as listed here (This page lists a few libraries to integrate Laravel with Swoole).

deminy avatar Oct 05 '22 18:10 deminy