队列执行报错 Undefined property: App\Jobs\TranslateSlug::$topic
如题
代码如下:
TopicObserver.php
<?php
namespace App\Observers;
use App\Models\Topic;
use App\Handlers\SlugTranslateHandler;
use App\Jobs\TranslateSlug;
// creating, created, updating, updated, saving,
// saved, deleting, deleted, restoring, restored
class TopicObserver
{
public function saving(Topic $topic)
{
$topic->body = clean($topic->body, 'user_topic_body');
$topic->excerpt = make_excerpt($topic->body);
}
public function saved(Topic $topic)
{
// 如 slug 字段无内容,即使用翻译器对 title 进行翻译
if ( ! $topic->slug) {
// 推送任务到队列
dispatch(new TranslateSlug($topic));
}
}
public function creating(Topic $topic)
{
//
}
public function updating(Topic $topic)
{
//
}
}
app\Jobs\TranslateSlug.php
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\Topic;
use App\Handlers\SlugTranslateHandler;
class TranslateSlug implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $topic;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Topic $topic)
{
// 队列任务构造器中接收了 Eloquent 模型,将会只序列化模型的 ID
$this->topic = $topic;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
// 请求百度 API 接口进行翻译
$slug = app(SlugTranslateHandler::class)->translate($this->topic->title);
// 为了避免模型监控器死循环调用,我们使用 DB 类直接对数据库进行操作
\DB::table('topics')->where('id', $this->topic->id)->update(['slug' => $slug]);
}
}
推荐文章: