在大多数情况下,PHP 是“同步的”,这意味着理论上您不能对任何函数进行“同时调用”。
但是,存在一些解决方法可以使这项工作正常进行。
PHP 是一种脚本语言。因此,当您在控制台中启动它时:
php -r "echo 'Hello World';"
一个 PHP 进程 被启动,在这个进程中发生的任何事情都会同步执行。
所以这里的解决方案是启动各种 PHP 进程,以便能够同时运行函数。
想象一个 SQL 表,其中放置了所有要同时执行的函数。然后,您可以运行 10 个实际“同时”工作的 php 进程。
Laravel 提供了一个开箱即用的解决方案。正如@Anton Gildebrand 在 cmets 中提到的那样,它被称为“队列”。
您可以在此处找到文档: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
从命令行,它将执行您的任务。
您可以根据需要执行任意数量的工作人员...
我希望这会有所帮助!