本书未发布

队列任务

未匹配的标注

就像上一节中的邮件门面一样,在包中实现任务与在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...

上一篇 下一篇
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~