Lesson 32 of 45 · Persistence, Flow and State
The Pipeline Pattern
Middleware is already a pipeline
Every Laravel middleware you have written has the same shape: handle(Request $request, Closure $next). It looks at the request, calls $next($request) to pass it on, or returns early. The class that runs them is Illuminate\Pipeline\Pipeline. In the Laravel 13.x source, Illuminate\Foundation\Http\Kernel builds new Pipeline($this->app) (the Illuminate\Routing\Pipeline subclass), sends the request through the global middleware, and the router does the same with route middleware.
Nothing in that class knows about HTTP. It takes any object, an ordered list of steps and a final destination, and that makes it useful for work in your own domain. This lesson uses it to price a hotel stay.
Pipeline versus Chain of Responsibility
The Gang of Four book states the intent of Chain of Responsibility in two sentences: "Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it."
The wiring is the same as a pipeline: objects in a line. In the classic chain each handler holds a reference to the next one, and Laravel's pipeline hands each step the next one as a closure, $next. The difference is what the objects usually do. In a classic chain the first handler that can deal with the request does so and the chain ends there. In a Laravel pipeline most steps do their own piece of work and then call $next, so every step runs. A step can still end the pipeline by not calling $next, as RedirectIfAuthenticated does when it redirects a signed-in user.
Reach for a pipeline when a job splits into steps that change independently of each other and the order between them matters. A price built from a base rate, a seasonal change, a discount and a tax fits: finance changes the tax rule without touching the discount rule.
Pricing a stay in four steps
The example prices a stay. StayQuote is the object that travels through the pipeline. It is immutable, so each step returns a new quote through withTotal() and never edits the one it received. It also records the name of each step that changed the total, which makes the result easy to inspect in a test.
<?php
declare(strict_types=1);
namespace App\Pricing;
use App\Billing\Money;
use App\Reservations\DateRange;
final readonly class StayQuote
{
/** @param list<string> $applied Names of the steps that changed the total, in order. */
private function __construct(
public DateRange $stayDates,
public Money $nightlyRate,
public Money $total,
public array $applied,
) {}
public static function start(DateRange $stayDates, Money $nightlyRate): self
{
return new self($stayDates, $nightlyRate, Money::zero($nightlyRate->currency), []);
}
public function withTotal(Money $total, string $step): self
{
return new self($this->stayDates, $this->nightlyRate, $total, [...$this->applied, $step]);
}
}Each step is a class with one handle() method. BaseRate reuses the PriceCalculator interface from the SOLID lesson, so a weekend-rate calculator can be swapped in through the container. The other three steps stand on their own.
<?php
declare(strict_types=1);
namespace App\Pricing;
use Closure;
final readonly class BaseRate
{
public function __construct(private PriceCalculator $calculator) {}
public function handle(StayQuote $quote, Closure $next): StayQuote
{
$total = $this->calculator->calculate($quote->stayDates, $quote->nightlyRate);
return $next($quote->withTotal($total, 'base rate'));
}
}<?php
declare(strict_types=1);
namespace App\Pricing;
use Closure;
final readonly class SeasonalAdjustment
{
private const HIGH_SEASON_MONTHS = [7, 8];
private const HIGH_SEASON_SURCHARGE_PERCENT = 25;
public function handle(StayQuote $quote, Closure $next): StayQuote
{
if (! in_array($quote->stayDates->checkIn->month, self::HIGH_SEASON_MONTHS, true)) {
return $next($quote);
}
$surcharge = $quote->total->percentage(self::HIGH_SEASON_SURCHARGE_PERCENT);
return $next($quote->withTotal($quote->total->add($surcharge), 'high season'));
}
}<?php
declare(strict_types=1);
namespace App\Pricing;
use Closure;
final readonly class LongStayDiscount
{
private const MINIMUM_NIGHTS = 7;
private const DISCOUNT_PERCENT = 10;
public function handle(StayQuote $quote, Closure $next): StayQuote
{
if ($quote->stayDates->nights() < self::MINIMUM_NIGHTS) {
return $next($quote);
}
$discounted = $quote->total->applyDiscountPercent(self::DISCOUNT_PERCENT);
return $next($quote->withTotal($discounted, 'long stay'));
}
}<?php
declare(strict_types=1);
namespace App\Pricing;
use Closure;
final readonly class TouristTax
{
private const TAX_PERCENT = 5;
public function handle(StayQuote $quote, Closure $next): StayQuote
{
$tax = $quote->total->percentage(self::TAX_PERCENT);
return $next($quote->withTotal($quote->total->add($tax), 'tourist tax'));
}
}SeasonalAdjustment and LongStayDiscount skip their work when the stay does not qualify, but they still call $next. That call is how a step says "nothing for me here, keep going".
Running it with Laravel's Pipeline
StayPricing lists the steps as class names and hands them to the pipeline. The container is injected here, which the dependency injection lesson warns against because a class that pulls its collaborators from the container is using service location. This class needs the container only so the pipeline can build the steps from class names, and the plain-PHP version later in this lesson avoids it. A new Pipeline is built for each quote, because send() stores the object on the pipeline instance and a shared instance would carry one caller's quote into the next call.
<?php
declare(strict_types=1);
namespace App\Pricing;
use App\Billing\Money;
use App\Reservations\DateRange;
use Illuminate\Contracts\Container\Container;
use Illuminate\Pipeline\Pipeline;
final readonly class StayPricing
{
/** Order matters: tax applies to the discounted total, so it runs last. */
private const STEPS = [
BaseRate::class,
SeasonalAdjustment::class,
LongStayDiscount::class,
TouristTax::class,
];
public function __construct(private Container $container) {}
public function quote(DateRange $stayDates, Money $nightlyRate): StayQuote
{
return (new Pipeline($this->container))
->send(StayQuote::start($stayDates, $nightlyRate))
->through(self::STEPS)
->thenReturn();
}
}The source of Illuminate\Pipeline\Pipeline shows what happens to each entry in through(). A closure or other callable is called directly. An object is used as it is. A string is resolved with $container->make(), so BaseRate receives its PriceCalculator by constructor injection. The container needs a binding for that interface. PricingServiceProvider binds it to StandardPriceCalculator from the SOLID lesson. List the provider in bootstrap/providers.php:
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Pricing\PriceCalculator;
use App\Pricing\StandardPriceCalculator;
use Illuminate\Support\ServiceProvider;
final class PricingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(PriceCalculator::class, StandardPriceCalculator::class);
}
}The pipeline then calls handle() on the resolved object, or invokes it if it has no such method. thenReturn() runs the steps and returns whatever comes out of the last one. then() takes a destination closure when you want to do something with the result instead.
For a seven-night stay from 10 July 2026 at 100.00 per night, the steps produce a base of 700.00, add 25 percent for high season to reach 875.00, take 10 percent off for the long stay to reach 787.50, and add 5 percent tax for 826.87. percentage() rounds the tax down, so 39.375 becomes 39.37. The applied list reads base rate, high season, long stay, tourist tax.
A test resolves StayPricing from the container, so the binding and the step order are both exercised. It prices the seven-night stay above and the three-night stay that comes back in the pitfalls section:
<?php
declare(strict_types=1);
namespace Tests\Feature\Pricing;
use App\Billing\Currency;
use App\Billing\Money;
use App\Pricing\StayPricing;
use App\Reservations\DateRange;
use Carbon\CarbonImmutable;
use Tests\TestCase;
final class StayPricingTest extends TestCase
{
public function test_a_seven_night_stay_gets_every_step(): void
{
$pricing = $this->app->make(StayPricing::class);
$quote = $pricing->quote(
DateRange::ofNights(CarbonImmutable::parse('2026-07-10'), 7),
Money::fromCents(10000, Currency::usd()),
);
$this->assertSame(82687, $quote->total->amountInCents);
$this->assertSame(['base rate', 'high season', 'long stay', 'tourist tax'], $quote->applied);
}
public function test_a_three_night_stay_skips_the_long_stay_discount_but_pays_the_tax(): void
{
$pricing = $this->app->make(StayPricing::class);
$quote = $pricing->quote(
DateRange::ofNights(CarbonImmutable::parse('2026-07-10'), 3),
Money::fromCents(10000, Currency::usd()),
);
$this->assertSame(39375, $quote->total->amountInCents);
$this->assertSame(['base rate', 'high season', 'tourist tax'], $quote->applied);
}
}A step that acts after $next
Every step so far changes the quote before passing it on. A step can also call $next first and act on what comes back. LogFinishedQuote records the finished quote and returns it unchanged:
<?php
declare(strict_types=1);
namespace App\Pricing;
use Closure;
use Psr\Log\LoggerInterface;
final readonly class LogFinishedQuote
{
public function __construct(private LoggerInterface $logger) {}
public function handle(StayQuote $quote, Closure $next): StayQuote
{
$priced = $next($quote);
$this->logger->info('Stay priced', [
'nights' => $priced->stayDates->nights(),
'total_cents' => $priced->total->amountInCents,
'applied' => $priced->applied,
]);
return $priced;
}
}Put it first in STEPS. Its code runs last, after the other four have returned, so it sees the final total, and it adds nothing to applied. The LogCommandDuration pipe from the Command Bus lesson has the same shape: it does its work around $next and returns what the rest of the chain returned.
The same pipeline without Laravel
A Symfony project or a framework-free one can do without the Laravel class. The core is a reduce over the steps, which is how Pipeline::then() builds its chain too: it reverses the step list and wraps the destination in one closure per step.
<?php
declare(strict_types=1);
namespace App\Framework\Pipeline;
use Closure;
final readonly class Pipeline
{
/** @param list<callable(mixed, Closure): mixed> $steps */
public function __construct(private array $steps) {}
public function process(mixed $passable, Closure $destination): mixed
{
$run = array_reduce(
array_reverse($this->steps),
fn (Closure $next, callable $step): Closure => fn (mixed $current): mixed => $step($current, $next),
$destination,
);
return $run($passable);
}
}The wiring passes the steps as closures created with first-class callable syntax, and the destination returns the quote unchanged:
<?php
declare(strict_types=1);
namespace App\Pricing;
use App\Billing\Money;
use App\Framework\Pipeline\Pipeline;
use App\Reservations\DateRange;
final readonly class PlainStayPricing
{
public function __construct(
private BaseRate $baseRate,
private SeasonalAdjustment $seasonal,
private LongStayDiscount $longStay,
private TouristTax $touristTax,
) {}
public function quote(DateRange $stayDates, Money $nightlyRate): StayQuote
{
$pipeline = new Pipeline([
$this->baseRate->handle(...),
$this->seasonal->handle(...),
$this->longStay->handle(...),
$this->touristTax->handle(...),
]);
return $pipeline->process(
StayQuote::start($stayDates, $nightlyRate),
fn (StayQuote $quote): StayQuote => $quote,
);
}
}It gives the same totals as the Laravel version. What you lose is container resolution of steps from class names, so the constructor lists the steps and the container builds them.
Pipeline or decorator
The Decorator pattern lesson stacked MetricsPayments over LoggingPayments over RetryingPayments. The stack and a pipeline look alike: each layer wraps the next and decides when to call it. The two differ in three ways.
The contract. Every decorator implements the same interface as the thing it wraps and forwards all of its methods. A pipeline step has one method, and it works on a value that passes through, not on a service.
When the list is fixed. The decorator stack is built once, in a service provider. A pipeline's list is data, so one call can run
[BaseRate::class, TouristTax::class]and another can run all four.What it sits on. A decorator wraps a service's interface. A pipeline runs a value through an ordered list.
Use a decorator when one object needs extra behavior around its methods. Use a pipeline when a value goes through ordered transformations.
Pitfalls
A step that forgets $next. The pipeline has no check that a step called $next. In carry(), the step's return value is what the closure returns, so a step that returns without calling $next ends the pipeline and its return value becomes the pipeline's result. Nothing throws, because the return type is still StayQuote. This variant of the discount has the mistake, in the early return:
<?php
declare(strict_types=1);
namespace App\Pricing;
use Closure;
final readonly class ForgetfulLongStayDiscount
{
private const MINIMUM_NIGHTS = 7;
private const DISCOUNT_PERCENT = 10;
public function handle(StayQuote $quote, Closure $next): StayQuote
{
if ($quote->stayDates->nights() < self::MINIMUM_NIGHTS) {
return $quote;
}
$discounted = $quote->total->applyDiscountPercent(self::DISCOUNT_PERCENT);
return $next($quote->withTotal($discounted, 'long stay'));
}
}A three-night stay in July now stops at the discount step. The quote comes back as 375.00 with applied reading base rate, high season, and the tax of 18.75 is missing. The correct total is 393.75. A test that prices one short stay and one long stay and compares the totals catches this. A test of only the discount step will not, because it never sees what the later steps do.
Steps that rely on each other's side effects. If TouristTax needs to know whether the discount ran, do not let LongStayDiscount set a flag somewhere else. Put the fact on the quote, as applied does, so every step reads from the object it receives. Order dependencies stay in the STEPS list, with a test for the expected totals.
Mutating the passable. If StayQuote had public setters, a step could change the quote the caller still holds, and every later step would see the change without knowing who made it. That is the shared-state problem from the Immutable Objects lesson. With an immutable passable, a step that wants a change builds a new one.
The one thing to remember
A pipeline passes one object through small, ordered steps that each act, pass it on with $next, or stop. Use it when the steps change independently, the order matters, and the object is immutable so no step can change what another one sees.
Related Links
- Middleware (Laravel 13.x)Laravel's documentation of the handle and $next shape, including steps that return early and steps that act after the request is handled.
- Chain of ResponsibilityA write-up of the classic pattern, including the variant where a handler can process a request and still pass it along.
- Chain of Responsibility in PHPA PHP example with login middleware that checks throttling, user existence and role in order.
- Design Patterns: Chain of Responsibility (InformIT)An excerpt from the Gang of Four book with the original statement of the pattern's intent.