juststeveking/laravel-business-process

Laravel Business Process 是一种简单、清晰的方式来使用 Laravel Pipeline 运行业务流程,以结构化和类型安全的方式。

0.0.1 2023-04-27 09:59 UTC

This package is auto-updated.

Last update: 2024-08-27 13:28:12 UTC


README

Latest Version Software License Run Tests PHP Version Total Downloads

Laravel Business Process 是一种简单、清晰的方式来使用 Laravel Pipeline 运行业务流程,以结构化和类型安全的方式。

此包受到我为 Laravel News 编写的教程的启发:Laravel 中的操作之后

安装

composer require juststeveking/laravel-business-process

使用

要开始使用此包,您只需创建一个新的流程类

use JustSteveKing\BusinessProcess\Process;

final class PurchaseProduct extends Process
{
    protected array $tasks = [
        CheckStockLevel::class,
        ProcessOrder::class,
        DecreaseStockLevel::class,
        NotifyWarehouse::class,
        EmailCustomer::class,
    ];
}

我们的流程类注册了需要完成的任务,以便运行此流程,每个任务都必须实现此包附带的可实现的 TaskContract 接口。

use JustSteveKing\BusinessProcess\Contracts\TaskContract;

final class CheckStockLevel implements TaskContract
{
    public function __invoke(ProcessPayload $payload, Closure $next): mixed
    {
        // perform your logic here with the passed in payload.
        
        return $next($payload);
    }
}

您的任务是标准的类,Laravel 的 Pipeline 类期望这些类。

有效载荷是一个实现 ProcessPayload 接口的类,表示它是一个流程的有效载荷。它们是简单的普通 PHP 类,无需添加方法。

use JustSteveKing\BusinessProcess\Contracts\ProcessPayload;

final class PurchaseProductPayload implements ProcessPayload
{
    public function __construct(
        // add whatever public properties you need here
        public int $product,
        public int $user,
        public int $order,
    ) {}
}

最后,我们可以在控制器/作业/cli 中调用此流程,您需要的地方。

final class PurchaseController
{
     public function __construct(
        private readonly PurchaseProduct $process,
     ) {}
     
     public function __invoke(PurchaseRequest $request, int $product): JsonResponse
     {
        try {
            $this->process->run(
                payload: $request->payload(),
            );
        } catch (Throwable $exception) {
            // Handle exception
        }
        
        // return response.
     }
}

测试

要运行测试

composer run test

致谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅许可证文件