yogameleniawan/realtime-job-batching

使用Pusher为Laravel实现实时进度作业批处理

v1.1.2 2024-07-28 10:31 UTC

This package is auto-updated.

Last update: 2024-09-28 10:46:27 UTC


README

banner

实时作业批处理预览

Untitled

目录列表

要求

配置

迁移表

  • 创建迁移作业表
php artisan queue:table
  • 创建迁移作业批处理表
php artisan queue:batches-table
  • 迁移表
php artisan migrate

安装包

composer require yogameleniawan/realtime-job-batching

Pusher配置

  • 安装Pusher PHP SDK
composer require pusher/pusher-php-server
PUSHER_APP_ID=your_pusher_app_id
PUSHER_APP_KEY=your_pusher_app_key
PUSHER_APP_SECRET=your_pusher_app_secret
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1

实现

创建服务仓库

  • your_project\app\Repositories上创建仓库类,例如:VerificationRepository.php

现在您有了仓库类 your_project\app\Repositories\VerificationRepository.php

  • 在您的仓库类中添加 implements RealtimeJobBatchInterface

  • 不要忘记导入接口 use YogaMeleniawan\JobBatchingWithRealtimeProgress\Interfaces\RealtimeJobBatchInterface;

  • 该接口有2个方法。因此,您应该实现这些方法

    public function get_all(): Collection 在这个函数中,您可以获取数据库中的所有数据并将其作为Collection返回。为什么应该返回到Collection?首先,数据将通过foreach方法循环,然后逐个添加到作业中,然后逐个执行。

    public function save($data): void 在这个函数中,您可以实现自己的业务逻辑来更新/删除/或其他您想要的操作。因此,这个函数没有返回数据,所以这个函数必须是void类型。

  • 这是仓库类的示例

image

创建控制器函数

  • 创建处理您作业过程的函数,例如:image
use YogaMeleniawan\JobBatchingWithRealtimeProgress\RealtimeJobBatch;
use App\Repositories\VerificationRepository;

RealtimeJobBatch::setRepository(new VerificationRepository())
                    ->execute(name: 'User Verification')

VerificationRepository() 是您之前创建的服务仓库,所以不要忘记导入此类 use App\Repositories\VerificationRepository;

  • RealtimeJobBatch方法说明
    • setRepository(RealtimeJobBatchInterface $repository):object 是一个方法,用于实现您想要使用的仓库类并将其返回为对象。因此,您可以使用 RealtimeJobBatch 类在另一个服务中使用不同的仓库。
    • execute($name): object 是一个方法,用于执行具有您自定义名称的作业服务。此方法将返回对象。

设置javascript

  • 将此脚本添加到您的视图(blade)中。对于另一个视图(React/Vue/Etc),您可以在此链接中查看 设置Pusher
  • Blade脚本
    <script src="https://js.pusher.com/7.2/pusher.min.js"></script>
    <script>
        var pusher = new Pusher('YOUR_PUSHER_APP_KEY', {
        cluster: 'mt1'
        });

        var channel = pusher.subscribe('channel-job-batching');
        channel.bind('broadcast-job-batching', function(data) {
            console.log(data)
        });

        var channel_finish = pusher.subscribe('channel-finished-job');
        channel_finish.bind('request-finished-job', function(data) {
            if (data.finished == true) {
                // reset your progress bar
            }
        });
    </script>
  • 来自Pusher的响应
{
  "finished": false,
  "progress": 10,
  "pending": 90,
  "total": 100,
  "data": {}
},

变更日志

请参阅变更日志获取有关最近更改的更多信息。

致谢

许可

MIT 许可协议(MIT)。请参阅许可文件以获取更多信息。