Skip to content

Instantly share code, notes, and snippets.

@gemmadlou
Forked from jeffochoa/1.ProcessClass.php
Created February 24, 2021 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gemmadlou/7480003c4d9d2812bd6ccca45039e790 to your computer and use it in GitHub Desktop.
Save gemmadlou/7480003c4d9d2812bd6ccca45039e790 to your computer and use it in GitHub Desktop.
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