ghofurgiovany/pipeline

v2 2022-10-27 02:02 UTC

This package is not auto-updated.

Last update: 2024-09-27 10:09:50 UTC


README

Example code showcasing the Pipeline package using the with transaction method and the pipable trait

安装

通过 composer 安装

composer require GhofurGiovany/pipeline

在管道中发送管道

在配置管道时,你可以发送一个类字符串数组、可调用的对象、闭包、具有 handle() 方法的对象,或任何其他通过 is_callable() 的类型。

use GhofurGiovany\Pipeline\Pipeline;

class RegisterController
{
    public function store(StoreRegistrationRequest $request)
    {
        return Pipeline::make()
            ->send($request->all())
            ->through([
                RegisterUser::class,
                AddMemberToTeam::class,
                SendWelcomeEmail::class,
            ])
            ->then(fn ($data) => UserResource::make($data));
    }
}

另一种方法是将其实现为数据对象上的 trait。 (如果你真的想的话,你甚至可以在你的 FormRequest 对象上实现它。)

use GhofurGiovany\Pipeline\Pipable;

class UserDataObject
{
    use Pipable;

    public string $name;
    public string $email;
    public string $password;
    // ...
}

class RegisterController
{
    public function store(StoreRegistrationRequest $request)
    {
        return UserDataObject::fromRequest($request)
            ->pipeThrough([
                RegisterUser::class,
                AddMemberToTeam::class,
                SendWelcomeEmail::class,
            ])
            ->then(fn ($data) => UserResource::make($data));
    }

    // you also can pipe the request

    return $request->pipe()
            ->withTransaction()
            ->through([
                RegisterUser::class,
                AddMemberToTeam::class,
                SendWelcomeEmail::class,
            ])
            ->then(fn ($data) => UserResource::make($data));
}

为了与 Laravel 的 Pipeline 类保持兼容性,through() 方法可以接受一个调用者数组或多个参数,其中每个参数都是之前列出的调用者类型之一。然而,pipeThrough() trait 方法仅接受一个数组,因为它还有一个可选的第二个参数。

使用数据库事务

当你想在管道中使用数据库事务时,方法将根据你是否使用 trait 或 Pipeline 类而有所不同。

使用 Pipeline

Pipeline::make()->withTransaction()

withTransaction() 方法将告诉管道使用事务。当你调用 then()thenReturn() 方法时,将在执行管道之前开始数据库事务。如果在管道中遇到异常,事务将被回滚,因此不会将数据提交到数据库。假设管道成功完成,则提交事务。

当使用 trait 时,你可以将第二个参数传递给 pipeThrough() 方法

$object->pipeThrough($pipes, withTransaction: true);

测试

composer test