本书未发布

队列任务

未匹配的标注

就像上一节中的邮件门面一样,在包中实现任务与在 Laravel 应用程序中完成的工作流程非常相似。

创建一个任务#

首先,在包的 src/ 目录中创建一个新的 Jobs 目录,并添加一个 PublishPost.php 文件,该文件将负责更新 Postpublished_at 时间戳。以下是 handle() 方法的示例:

<?php

namespace JohnDoe\BlogPackage\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use JohnDoe\BlogPackage\Models\Post;

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

    public $post;

    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    public function handle()
    {
        $this->post->publish();
    }
}

测试调度作业#

在本示例,我们在已经测试过的 Post 模型上有一个 publish() 方法 (Post 的单元测试)。我们可以通过在 tests/unit 目录中添加新的 PublishPostTest.php 单元测试来轻松测试预期的行为。

在此测试中,我们可以利用 Bus 门面 提供的一个 fake() 辅助函数来模拟一个真实的实现。调度任务之后,我们可以在 Bus 门面上断言我们的 Job 已调度并且包含正确的 Post

<?php

namespace JohnDoe\BlogPackage\Tests\Unit;

use Illuminate\Support\Facades\Bus;
use JohnDoe\BlogPackage\Jobs\PublishPost;
use JohnDoe\BlogPackage\Models\Post;
use JohnDoe\BlogPackage\Tests\TestCase;

class PublishPostTest extends TestCase
{
    /** @test */
    public function it_publishes_a_post()
    {
        Bus::fake();

        $post = factory(Post::class)->create();

        $this->assertNull($post->published_at);

        PublishPost::dispatch($post);

        Bus::assertDispatched(PublishPost::class, function ($job) use ($post) {
            return $job->post->id === $post->id;
        });
    }
}

随着测试的通过,您可以在包中安全地使用此任务。

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/laravel-package...

译文地址:https://learnku.com/docs/laravel-package...

上一篇 下一篇
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~