0

我的特质中有这样的功能:

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

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

}

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

4

1 回答 1

1

在大多数情况下,PHP 是“同步的”,这意味着理论上您不能对任何函数进行“同时调用”。

但是,存在一些解决方法可以使这项工作。

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

php -r "echo 'Hello World';"

启动一个 PHP进程,在这个进程中发生的任何事情都会同步执行。

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

想象一个 SQL 表,其中放置了所有要同时执行的函数。然后,您可以运行 10 个实际“同时”工作的 php 进程。

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

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

laravel 的做法是创造“工作”。每个 Job 代表您要执行的功能。在这里,您的工作将是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...
    }
}

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

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

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

您可以根据需要执行任意数量的工作人员...

我希望这有帮助!

于 2017-10-24T15:06:45.350 回答