Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Understanding Laravel pipelines
<?php
namespace App\Features;
use App\Features\FirstTask;
use App\Features\SecondTask;
use Illuminate\Pipeline\Pipeline;
// *Naming things is hard* ... So, this is a class called `ProcessClass` that `run()` some text ¯\_(ツ)_/¯
class ProcessClass
{
protected $pipes;
public function __construct()
{
$this->pipes = $this->loadPipes();
}
public function loadPipes()
{
return [
FirstTask::class,
SecondTask::class
];
}
public function run($text)
{
return app(Pipeline::class)
->send($text)
->through($this->pipes)
->then(function ($text) {
return $text . "finally";
});
}
}
<?php
namespace App\Features;
use Closure;
class FirstTask
{
/**
* Changes the given text and return the result
**/
public function handle($text, Closure $next)
{
return $next($text . ' [first task] ');
}
}
<?php
namespace App\Features;
use Closure;
class SecondTask
{
/**
* Changes the given text and return the result
**/
public function handle($text, Closure $next)
{
return $next($text . ' [second task] ');
}
}
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Features\ProcessClass;
class PipelineTest extends TestCase
{
public function testExample()
{
$text = 'Initial test';
$object = new ProcessClass($text);
$result = $object->run($text);
$this->assertEquals('Initial test [first task] [second task] finally', $result);
}
}
PHPUnit 6.2.4 by Sebastian Bergmann and contributors.

...                                                                 3 / 3 (100%)

Time: 136 ms, Memory: 14.00MB

OK (3 tests, 3 assertions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.