Php Laravel-将函数的一部分转换为排队语句
我想在我的控制器中对函数的一部分进行排队,主要是因为它访问第三方API并根据所述请求计算某些信息。我也想这样做,以增加我对队列的了解 我要排队的代码是: 如果语句为Php Laravel-将函数的一部分转换为排队语句,php,laravel,laravel-5,task-queue,Php,Laravel,Laravel 5,Task Queue,我想在我的控制器中对函数的一部分进行排队,主要是因为它访问第三方API并根据所述请求计算某些信息。我也想这样做,以增加我对队列的了解 我要排队的代码是: 如果语句为$postcode和$clinic ID(在语句上方计算),则需要使用此推送的唯一变量 到目前为止,我已经创建了队列表并对其进行了迁移 然后我运行命令:php-artisan-make:job-GetClinicLatAndLongPoints-queued 我的问题是,如何将此函数放入GetClinicLatAndLongPoint
$postcode
和$clinic ID
(在语句上方计算),则需要使用此推送的唯一变量
到目前为止,我已经创建了队列
表并对其进行了迁移
然后我运行命令:php-artisan-make:job-GetClinicLatAndLongPoints-queued
我的问题是,如何将此函数放入GetClinicLatAndLongPoints
中,包括传递两个变量来实现这一点
到目前为止,我已经:
public function handle(Clinic $clinic, $postcode)
{
}
但我不知道该怎么安排!非常感谢您的任何指导。您可以将您的诊所
模型的实例和邮政编码传递给您工作的构建者,这可能与
namespace App\Jobs;
use App\Clinic;
use App\Jobs\Job;
use GuzzleHttp\Client;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
class GetClinicLatAndLongPoints extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels;
private $clinic;
private $postcode;
public function __construct(Clinic $clinic, $postcode)
{
$this->clinic = $clinic; // Laravel will automatically deserialize the model instance
$this->postcode = $postcode;
}
public function handle()
{
$coordinates = $this->getCoordinates($this->postcode);
if (! is_null($coordinates)) {
// You may want to add error handling
$this->clinic->latitude = $coordinates['latitude'];
$this->clinic->longitude = $coordinates['longitude'];
$this->clinic->save();
}
}
private function getCoordinates($postcode)
{
$client = new Client(['base_uri' => 'https://api.postcodes.io/','timeout' => 2.0, 'verify' => false]);
$response = json_decode($client->get('postcodes/'.$postcode)->getBody()->getContents());
if (! $response || json_last_error() !== JSON_ERROR_NONE) {
return null;
}
if ($response->status == 200 &&
isset($response->result->latitude) &&
isset($response->result->longitude)) {
return [
'latitude' => $response->result->latitude,
'longitude' => $response->result->longitude
];
}
return null;
}
}
在控制器中,您可以分派作业
if ($clinic->postcode != $postcode) {
$this->dispatch(new GetClinicLatAndLongPoints($clinic, $postcode));
}
另一方面:尽管Laravel附带了数据库队列驱动程序,但在生产中使用它并不是一个好主意。最好使用其中一个,即…您使用的是哪种版本的laravel,您已标记了这两个版本!哎呀,对不起!我已经移除了拉威尔4号。我正在使用最新的Laravel 5.1。*!您是否尝试过将其复制粘贴到句柄函数中?还要确保您的队列正在运行(php artisan queue:listen
)是的,但我不确定如何传递必要的变量,以使if语句
正确工作。我认为L5支持雄辩的模型实例的对象序列化。。只需发送模型,看看会发生什么;)这是一个多么奇妙的回答,而且非常清楚!非常感谢您的帮助@peterm!作为对你答案的补充,我必须添加use-App\Jobs\GetClinicLatAndLongPoints代码>发送到控制器。我目前遇到的唯一问题是GetClinicLatAndLongPoints
script-“GetClinicLatAndLongPoints.php第13行中的FatalErrorException:未找到类“App\Jobs\Job”
。GetClinicLat。。。不是在“作业”文件夹中,比如说,只是Jobs
文件夹。我不确定这是为什么?结果是我没有默认的Job.php
,它应该随Laravel一起提供!复制它可以使一切正常工作。再次感谢。
if ($clinic->postcode != $postcode) {
$this->dispatch(new GetClinicLatAndLongPoints($clinic, $postcode));
}