编程

在 Laravel 中集成 ReactPHP 服务

19 2025-07-09 04:01:00

创建命令

创建一个 Laravel 命令

php artisan make:command SaleServer --command=bidserver:sale

该命令将生成一个运行  ReactPHP 服务的 daemon。

调用服务器

此命令使用 HTTP post 从 Livewire 组件中调用:

Http::asForm()->post(config('auctions.SALE_SERVER_URL') . ':' .  config('auctions.SALE_SERVER_PORT') . '/buy', [
    'auction_id' => $this->auction->id,
    'item_id' => $this->item->id,
    'user' => $this->user->id,
    'price' => $bid_received['price'],
]);   

服务器

该命令创建了一个 ReactPHP 服务器,来接收调用。

<?php

namespace App\Console\Commands;


use Illuminate\Console\Command;
use React\Http\Server;
use React\Http\Message\Response;
use React\EventLoop\Factory;
use Psr\Http\Message\ServerRequestInterface;
use React\Socket\SocketServer;

class SaleServer extends Command
{

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'bidserver:sale';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Sale bid server';

/**
 * Execute the console command.
 */
public function handle()
{
    $loop = Factory::create();
    $server = new Server(function (ServerRequestInterface $request) {

        $path = $request->getUri()->getPath();
        $method = $request->getMethod();

                //Check if the path and method of the call are correct
        if ($path == '/buy'  && $method === 'POST') {

                    //Extract the call parameters
        $auction_id = $request->getParsedBody()['auction_id'] ?? null;
        $item_id = $request->getParsedBody()['item_id'] ?? null;
        $user = $request->getParsedBody()['user'] ?? null; 
        $bid_price = $request->getParsedBody()['price'] ?? null; 

          //Broadcast a response
          broadcast(new BuyAccepted($auction_id, $item_id, $user))->toOthers();

                    return Response::plaintext('bid processed')->withStatus(Response::STATUS_OK);   

    }             

    return Response::plaintext('Not found')->withStatus(Response::STATUS_NOT_FOUND);

        });

    $socket = new SocketServer('0.0.0.0:' . config('auctions.SALE_SERVER_PORT'));
    $server->listen($socket);

  $loop->run();

}
}

Daemon

添加 daemon 运行如下命令:

php artisan bidserver:sale

 

相关推荐:

下一篇