如何使用Laravel管道?

ygya80vv  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(44)

我有一个User模型,它附加了几个外部服务(Services模型,多通信),我事先不知道会有多少个外部集成,它们有什么设置(每个服务都是作为一个单独的类实现的,集成设置在Services模型的属性中描述)。
我想使用管道模板。但我找不到任何好的Laravel代码示例和文档。
它应该看起来像

$integrations = $user->integrations;
if ($integrations->count()) {
   return app(Pipeline::class)
      -> send($user)
      -> through($integrations)
      -> thenReturn();
}

字符串
但我不明白它是如何工作的.如何实现管道类?

kq0g1dla

kq0g1dla1#

每个管道本质上是一个处理一段逻辑的类。该类应该定义一个handle方法:

namespace App\Pipes;

class SomeServiceIntegration
{
    public function handle($user, \Closure $next)
    {
        // ur codes
        
        return $next($user);
    }
}

字符串
您可以使用Pipeline类通过定义的管道发送对象:

use Illuminate\Pipeline\Pipeline;

$integrations = $user->integrations;

if ($integrations->count()) {
    // at here., you need to get the classes (pipes) for each integration
    $pipes = $integrations->map(function ($integration) {
        return $integration->serviceClass; // i assume that you store the full class path in the 'serviceClass' attribute
    })->toArray();

    return app(Pipeline::class)
        ->send($user)
        ->through($pipes)
        ->thenReturn();
}


如果每个服务都有自己的设置,您可能需要添加设置:

$pipes = $integrations->map(function ($integration) {
    return app($integration->serviceClass, ['settings' => $integration->settings]);
})->toArray();


并调整SomeServiceIntegration类以接受设置:

namespace App\Pipes;

class SomeServiceIntegration
{
    protected $settings;

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

    public function handle($user, \Closure $next)
    {
        // u can use $this->settings here easily :○

        return $next($user);
    }
}

相关问题