Laravel 同时启动函数

Laravel simultaneous launch functions

我的性格中有这样的功能:

public function cupPlayMatch(Season $season, $round_id)
{

    foreach($season->cups as $cup)
    {
        $this->cupPlay($cup, $round_id);
    }

}

当第一个杯子结束时,第二个杯子开始播放。我怎样才能同时开始玩我所有的杯子?

在大多数情况下,PHP 是 "synchronous",这意味着您理论上无法对任何函数进行 "simultaneous calls"。

但是,存在一些解决方法可以使此工作正常进行。

PHP是一种脚本语言。因此,当您在控制台中启动它时:

php -r "echo 'Hello World';"

A PHP process 被启动,并且在这个过程中发生的任何事情都是同步执行的。

所以这里的解决方案是启动各种 PHP 进程,以便能够同时 运行 运行。

想象一下 SQL table 中放置了所有要同时执行的函数。然后,您可以 运行 10 php 个实际工作的进程 "at the same time"。

Laravel 为这个问题提供了开箱即用的解决方案。正如@Anton Gildebrand 在评论中提到的那样,它被称为 "Queues"。

您可以在此处找到文档:https://laravel.com/docs/5.5/queues

laravel 的方法是创建 "jobs"。每个作业代表您要执行的一个功能。在这里,您的工作是 cupPlay.

这是从文档中粘贴的作业副本的基本示例:

<?php

namespace App\Jobs;

use App\Podcast;
use App\AudioProcessor;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $podcast;

    /**
     * Create a new job instance.
     *
     * @param  Podcast  $podcast
     * @return void
     */
    public function __construct(Podcast $podcast)
    {
        $this->podcast = $podcast;
    }

    /**
     * Execute the job.
     *
     * @param  AudioProcessor  $processor
     * @return void
     */
    public function handle(AudioProcessor $processor)
    {
        // Process uploaded podcast...
    }
}

当您将 worker 驱动程序配置为 运行 您的队列时,您只需要启动:

php artisan queue:work --queue=high,default

从命令行执行,它将执行您的任务。

并且您可以根据需要执行任意数量的 worker...

希望对您有所帮助!