Behavioral Patterns: Template Method, Chain of Responsibility, State, Command, Observer, Strategy, Iterator, Mediator, Memento, Visitor
"Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects." — refactoring.guru, Behavioral Design Patterns
Summary: Behavioral patterns answer "who does what, and who tells whom": how an algorithm is split into replaceable parts, how a request travels to the code that handles it, and how objects react to each other without knowing each other. Focus: The ten patterns in the title plus Interpreter, each with intent, structure diagram, participants, idiomatic Go (functions, interfaces, channels, iter.Seq, go/ast) and Laravel 13 (Pipeline, middleware, events, jobs, enums, LazyCollection, tagged bindings), consequences, confusions, distributed forms and tests. Learning goal: Recognise which of the eleven problems you have, pick the pattern (or the plain function) that solves it, implement it idiomatically in Go and Laravel, test it, and know which form it takes once the code is split into services.
This page is the complete reference for the eleven behavioral patterns of the Gang of Four catalogue. The origin of patterns and the three families are on Design Patterns: Introduction; object creation is on Creational Patterns; wrapping and composing objects (Decorator, Composite, Proxy, Facade) is on Structural Patterns; combining patterns in real systems and pattern abuse is on Patterns in Practice. Event loops and callbacks as a design issue are on Control Flow & Event Handling. Several patterns here are the mechanics behind SOLID: Strategy and Observer are the usual tools for Open–Closed, and Command and Mediator are how you keep Single Responsibility and Dependency Inversion once the code grows.
Page map
| If you are looking for | Go to |
|---|---|
| All eleven patterns in two tables | Everything in one minute |
| Why these patterns exist and what they cost | Why behavioral patterns exist |
| GoF 1994, refactoring.guru, Go 1.23 iterators, Laravel events | Where it comes from |
| Template Method, Chain of Responsibility, State, Command, Observer | The patterns, one by one |
| Strategy, Iterator, Mediator, Memento, Visitor, Interpreter | Strategy to Interpreter |
| Which stdlib or framework feature already is the pattern | Per-language view |
| Double dispatch, push vs pull, sync vs queued, undo stacks, transition tables | Mechanics |
| How to test each pattern | Testing each pattern |
| Order workflow, approval chain, undo/redo, audit log, event-driven modules | Solving the classic problems |
| Strategy vs State vs Template Method; Observer vs pub/sub vs Mediator; Command vs Job vs Transaction Script | Choosing |
| Observer becomes a broker, Command becomes a queue, State becomes a saga | In architecture |
| Order state machine + pipeline checkout + observers, Go and Laravel, with tests | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The eleven patterns. Every row is unpacked in the patterns section.
| Pattern | In plain words | Tiny example | Go idiom | Laravel idiom |
|---|---|---|---|---|
| Template Method | Fixed recipe, replaceable steps | Export: header, rows, footer | Function that takes a Steps interface | Abstract class with final method |
| Chain of Responsibility | Pass the request along until someone handles or stops it | Auth → log → rate limit → controller | func(http.Handler) http.Handler | Middleware, Pipeline::send()->through() |
| State | The object behaves differently in each state and moves between them | Order: pending → paid → shipped | State interface, or a transition table | Backed enum with transitions() |
| Command | A request turned into an object | "Capture payment for order 42" | Value with Do/Undo, or a closure | Queued Job, Bus::chain |
| Observer | Tell everyone who subscribed that something happened | Order paid → email, warehouse | Callbacks or channels | Events + listeners, Eloquent observers |
| Strategy | Swap one algorithm for another behind one interface | Flat vs weight-based shipping | A func value; slices.SortFunc | Interface + container binding or tags |
| Iterator | Walk a collection without knowing how it is stored | Range over a category tree | iter.Seq, iter.Seq2, iter.Pull | Generator, IteratorAggregate, LazyCollection |
| Mediator | Parts talk only to a hub, never to each other | Checkout form recomputes the summary | Coordinator struct or a goroutine owning state | Coordinator action; the event dispatcher |
| Memento | Save a snapshot you can restore, without exposing internals | Undo settings, document versions | Struct with unexported fields | document_versions table |
| Visitor | Add a new operation over a fixed set of types | Tax and CSV export over invoice lines | ast.Walk, ast.Inspect | accept()/visitX() classes |
| Interpreter | Each grammar rule is a class; evaluate the tree | Discount rules stored as JSON | Expr interface with Eval | Rule classes built by a parser |
The confusions everyone has. Each pair is resolved in Choosing.
| Looks like | Difference in one line |
|---|---|
| Strategy vs State | The caller picks a strategy; a state picks the next state itself |
| Strategy vs Template Method | Composition and runtime swap vs inheritance and compile-time steps |
| Observer vs pub/sub | Observer: subject knows its observers' interface, in-process; pub/sub: a broker in between, neither side knows the other |
| Observer vs Mediator | Observer is one-to-many broadcast; Mediator owns many-to-many coordination rules |
| Command vs Job vs Transaction Script | Command is the pattern; a Laravel Job is a queued Command; a Transaction Script is a procedure per request with no object for the request |
| Chain vs Decorator | Chain handlers may stop the request; a decorator always delegates and adds behaviour |
| Memento vs Command undo | Memento stores state before; Command stores how to reverse |
| Iterator vs Visitor | Iterator decides the order of elements; Visitor decides what to do with each type |
The map groups the patterns by the question they answer: what varies (an algorithm), what moves (a request), what is walked (a structure), and what is remembered (state).
Why behavioral patterns exist
Code that works on day one usually has its behaviour hard-wired: a switch on the shipping method, a controller that validates, authorises, charges and emails in one method, an if ($order->status === 'paid') in twenty places. Each new requirement edits that same code. Behavioral patterns move the varying part (an algorithm, a handler, a reaction, a state) into its own object or function, so a new requirement is a new piece instead of another branch.
| Hard-wired behaviour | Behaviour as replaceable parts |
|---|---|
| One place to read the whole flow | The flow is spread over several small types |
New case = edit a switch everywhere | New case = new type or function, registered once |
| Every reaction known to the sender | Sender announces; reactions subscribe |
| Tests need the whole flow | Each part tested alone with a fake neighbour |
| No indirection, fast to write | Indirection: more names, more jumps in the IDE |
| Risk: shotgun surgery and if-chains | Risk: pattern for a problem you do not have |
The analogy we reuse on this page: an airport. Security has several checkpoints in a row and any of them can turn you back (Chain of Responsibility). Your boarding pass is a request written on paper that any gate can process later (Command). The departure board announces a gate change to everyone watching it (Observer). Planes never talk to each other; they talk to the control tower (Mediator). A flight is boarding, departed or cancelled, and what you may do depends on that (State). The airline picks a pricing algorithm for your seat (Strategy). The baggage belt delivers suitcases one by one without showing you the sorting hall (Iterator).
Three common misunderstandings, up front
- "Patterns are classes you must write." A pattern is a solution to a recurring problem. In Go most behavioral patterns are a function type: a strategy is a
func, a chain isfunc(http.Handler) http.Handler, an iterator is aniter.Seq. Writing the textbook class diagram in Go is usually a smell. - "More patterns = better design." Each pattern adds indirection. A
switchwith three stable cases is clearer than a Strategy hierarchy. Use a pattern when the variation is real and recurring. - "Observer, pub/sub, event bus and message broker are the same thing." They share the idea of announcing instead of calling, but differ in who knows whom, whether delivery is synchronous, and whether the message survives a crash. See Observer vs pub/sub.
Where it comes from
The GoF book, 1994. Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides catalogued 23 patterns in three families. Its behavioral chapter (chapter 5) holds eleven: Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method and Visitor. We did not read the book's text for this page; publication facts are from Wikipedia's article on the book, which says it "started at a birds-of-a-feather session at the 1990 OOPSLA meeting" and "was originally published on 21 October 1994". The same article quotes the book's central rule, which explains why most behavioral patterns are built on composition:
"Favor 'object composition' over 'class inheritance'." — Gang of Four, as quoted on Wikipedia, Design Patterns
Template Method is the one behavioral pattern built on inheritance; every other one delegates to another object. That is also why Go, which has no inheritance, implements all of them comfortably.
What the authors would change. Wikipedia reports Erich Gamma saying in a 2009 InformIT interview that the authors would recategorise some patterns and add others such as dependency injection and null object. Patterns are a vocabulary, not a closed list.
refactoring.guru. Alexander Shvets's catalogue is the most-read modern restatement, with structure diagrams and examples in Go and PHP. Its intent sentences are quoted in each block below.
Language features that absorbed patterns. Go's sort.Interface and slices.SortFunc are Strategy; net/http middleware is Chain of Responsibility; go/ast ships a Visitor (ast.Walk) and its closure form (ast.Inspect). Go 1.23 added range-over-func, and the Go blog says "Range over function types is a new language feature in the Go 1.23 release", which made Iterator a language feature via the iter package. On the PHP side, generators made Iterator one keyword (yield); Laravel's docs say plainly that "Laravel's events provide a simple observer pattern implementation", and the Pipeline facade is Chain of Responsibility with the docs noting it "is very similar to middleware".
The patterns, one by one
Each block follows the same order: the intent, plain words, the usual wrong belief, the structure and participants, a timeline, real scenarios, Go and Laravel code, then consequences, when not to use it, confusions, distributed form and testing.
Template Method Important
"Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure." — refactoring.guru, Template Method
In plain words: the recipe is fixed (header, rows, footer) and only some steps change per variant.
Common misunderstanding: "Any base class with shared code is a Template Method." The point is the fixed order of steps owned by the base, with subclasses only filling holes. A base class whose subclasses override the whole flow is just inheritance.
Definition and participants: an abstract class with a template method (often final) that calls primitive operations (abstract steps) and hooks (steps with a default); concrete classes implement the steps. The base class calls the subclass, not the other way round, which is why it is called the Hollywood principle: "don't call us, we'll call you".
Caller ReportExporter (base) MarkdownExporter (subclass)
1 export(rows) -> header() -> "| id | name |"
2 row(r) x N -> "| 1 | mug |"
3 footer(count) -> "2 rows" (hook overridden)
4 <- full string order of 1..3 never changesReal scenario: report exporters (CSV, Markdown, PDF) sharing a fetch-format-write flow; importers that parse, validate and persist; test base classes (setUp, test, tearDown) in PHPUnit; framework lifecycles such as a Laravel Command::handle wrapped by the framework's run().
Go: no inheritance, so the skeleton becomes a function and the steps an interface. The order is still fixed in one place.
// Package templatemethod shows Template Method the Go way: the skeleton is a
// function, the varying steps are an interface (or func fields), not a base class.
package templatemethod
import (
"fmt"
"io"
"strings"
)
// Steps are the hooks the skeleton calls. Each exporter supplies its own.
type Steps interface {
Header(w io.Writer) error
Row(w io.Writer, cells []string) error
Footer(w io.Writer, rows int) error
}
// Export is the template method: the order of steps is fixed here and
// cannot be changed by an exporter.
func Export(w io.Writer, s Steps, rows [][]string) error {
if err := s.Header(w); err != nil {
return fmt.Errorf("header: %w", err)
}
for _, r := range rows {
if err := s.Row(w, r); err != nil {
return fmt.Errorf("row: %w", err)
}
}
return s.Footer(w, len(rows)) // hook with a default-like role
}
// CSV is one concrete set of steps.
type CSV struct{ Columns []string }
func (c CSV) Header(w io.Writer) error {
_, err := fmt.Fprintln(w, strings.Join(c.Columns, ","))
return err
}
func (CSV) Row(w io.Writer, cells []string) error {
_, err := fmt.Fprintln(w, strings.Join(cells, ","))
return err
}
func (CSV) Footer(io.Writer, int) error { return nil } // CSV has no footer
// Markdown reuses the same skeleton with different steps.
type Markdown struct{ Columns []string }
func (m Markdown) Header(w io.Writer) error {
_, err := fmt.Fprintf(w, "| %s |\n|%s\n", strings.Join(m.Columns, " | "),
strings.Repeat(" --- |", len(m.Columns)))
return err
}
func (Markdown) Row(w io.Writer, cells []string) error {
_, err := fmt.Fprintf(w, "| %s |\n", strings.Join(cells, " | "))
return err
}
func (Markdown) Footer(w io.Writer, rows int) error {
_, err := fmt.Fprintf(w, "\n%d rows\n", rows)
return err
}Laravel: an abstract class with a final template method and a hook with a default.
<?php
// Template Method: the base class fixes the order of steps (final export()),
// subclasses fill in the steps. In a real app each class has its own file.
namespace App\Reports;
use Illuminate\Support\Collection;
abstract class ReportExporter
{
/** The template method: final, so no subclass can reorder the steps. */
final public function export(Collection $rows): string
{
$out = $this->header();
foreach ($rows as $row) {
$out .= $this->row($row);
}
return $out.$this->footer($rows->count());
}
abstract protected function header(): string;
abstract protected function row(array $row): string;
/** Hook: a default that subclasses may override. */
protected function footer(int $count): string
{
return '';
}
}
final class CsvExporter extends ReportExporter
{
public function __construct(private readonly array $columns) {}
protected function header(): string
{
return implode(',', $this->columns)."\n";
}
protected function row(array $row): string
{
return implode(',', $row)."\n";
}
}
final class MarkdownExporter extends ReportExporter
{
public function __construct(private readonly array $columns) {}
protected function header(): string
{
return '| '.implode(' | ', $this->columns)." |\n|"
.str_repeat(' --- |', count($this->columns))."\n";
}
protected function row(array $row): string
{
return '| '.implode(' | ', $row)." |\n";
}
protected function footer(int $count): string
{
return "\n{$count} rows\n";
}
}Consequences: removes duplicated flow; enforces order. Costs: inheritance couples subclasses to the base; deep hierarchies make the flow hard to follow; a subclass can break the base's assumptions (an LSP risk).
When not to use: when variants differ in more than two or three steps (use Strategy objects per step), or when you need to switch the variant at runtime.
Related / confused with: Strategy vs Template Method; Factory Method is often a step inside a template method (Creational Patterns). No distributed form: it is a code-structure pattern.
Testing: test the skeleton once with a fake Steps; test each concrete exporter by its output (see export_test.go in the module).
Chain of Responsibility Must-know
"Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain." — refactoring.guru, Chain of Responsibility
In plain words: a line of checkpoints. Each one looks at the request and either handles it, rejects it, or passes it on.
Common misunderstanding: "In a chain only one handler acts." The GoF form stops at the first handler that can handle the request (the approval chain). The middleware form lets every handler act and pass on (logging, auth, rate limiting), with the right to stop. Both are Chain of Responsibility.
Definition and participants: a handler interface with a reference to the next handler (or a $next closure); concrete handlers; a client that builds the chain and sends the request to its head. The chain is assembled at runtime, so the order and membership are configuration.
Request GET /orders without token
1 Client -> Logging.handle logs "GET /orders", calls next
2 RequireToken.handle no Authorization header -> writes 401, returns
3 RateLimit, controller never run
4 Client <- 401 (Logging sees the response on the way back)Real scenario: HTTP middleware (auth, CSRF, CORS, rate limits, tenancy); purchase approval by amount (team lead, manager, CFO); support ticket escalation; fraud rules that each may block a payment; logging handlers that each decide whether to write a record.
Go: net/http middleware is the canonical chain. The Go docs describe the adapter it builds on: "The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers." The approval chain shows the "first one that can decide" form.
// Package chain shows Chain of Responsibility twice: the net/http middleware
// chain (every handler may stop the request) and an approval chain (the first
// handler that can decide, decides).
package chain
import (
"errors"
"log/slog"
"net/http"
)
// Middleware wraps a handler; the wrapped handler is "next".
type Middleware func(next http.Handler) http.Handler
// Chain applies middlewares so that the first one listed runs first.
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
// RequireToken stops the chain when the header is missing.
func RequireToken(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return // the request never reaches next
}
next.ServeHTTP(w, r)
})
}
// statusRecorder remembers the status code written by later handlers.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
// Logging always passes the request on and logs the result on the way back.
func Logging(log *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Info("request", "method", r.Method, "path", r.URL.Path, "status", rec.status)
})
}
}
// Approver is one link of an approval chain.
type Approver struct {
Role string
Limit int64 // highest amount this role may approve, in cents
Next *Approver
}
// ErrNoApprover means the request fell off the end of the chain.
var ErrNoApprover = errors.New("no approver can handle this amount")
// Approve walks the chain until a link can decide.
func (a *Approver) Approve(amount int64) (string, error) {
for link := a; link != nil; link = link.Next {
if amount <= link.Limit {
return link.Role, nil
}
}
return "", ErrNoApprover
}
// NewApprovalChain builds team lead -> manager -> CFO.
func NewApprovalChain() *Approver {
cfo := &Approver{Role: "cfo", Limit: 10_000_000}
manager := &Approver{Role: "manager", Limit: 500_000, Next: cfo}
return &Approver{Role: "team-lead", Limit: 50_000, Next: manager}
}Laravel: middleware is the chain for HTTP (Laravel docs: “It's best to envision middleware as a series of "layers" HTTP requests must pass through”); the Pipeline facade gives the same shape for any object. The lab uses Pipeline for checkout.
<?php
// Chain of Responsibility in Laravel: route middleware and the Pipeline facade
// are the same shape: each handler gets the input and a $next closure.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class EnsureApiToken
{
public function handle(Request $request, Closure $next): Response
{
if (! $request->bearerToken()) {
return response()->json(['message' => 'Unauthorized'], 401); // chain stops
}
return $next($request); // pass to the next handler
}
}
namespace App\Approvals;
use InvalidArgumentException;
/** A classic approval chain: the first link that can decide, decides. */
abstract class Approver
{
private ?Approver $next = null;
public function then(Approver $next): Approver
{
$this->next = $next;
return $next;
}
public function approve(int $cents): string
{
if ($this->canApprove($cents)) {
return static::class;
}
return $this->next?->approve($cents)
?? throw new InvalidArgumentException("No approver for {$cents}");
}
abstract protected function canApprove(int $cents): bool;
}
final class TeamLead extends Approver
{
protected function canApprove(int $cents): bool
{
return $cents <= 50_000;
}
}
final class Manager extends Approver
{
protected function canApprove(int $cents): bool
{
return $cents <= 500_000;
}
}
final class Cfo extends Approver
{
protected function canApprove(int $cents): bool
{
return $cents <= 10_000_000;
}
}
// Usage:
// $chain = new TeamLead;
// $chain->then(new Manager)->then(new Cfo);
// $chain->approve(200_000); // App\Approvals\ManagerConsequences: sender is decoupled from handlers; handlers are single-purpose and reorderable (SRP, OCP). Costs: a request may fall off the end unhandled (return an explicit error such as ErrNoApprover); order bugs are silent (auth after logging leaks unauthenticated paths into logs); long chains are hard to debug without tracing.
When not to use: a fixed two-step flow; or when every step must always run and none may stop (that is a plain list of functions, or Decorator).
Distributed form: an API gateway's filter chain; a routing slip where a message carries its list of processing steps.
Related / confused with: Decorator (Structural Patterns) always delegates, a chain link may stop; Observer vs Mediator for other sender/receiver shapes.
Testing: test each handler with a fake next (assert it was or was not called); test the assembled chain with httptest for order bugs and assert the outer Logging saw the 401 (chain_test.go).
State Must-know
"State is a behavioral design pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class." — refactoring.guru, State
In plain words: an order that is paid can ship; one that is pending cannot. Instead of if status == everywhere, each state is an object that knows what is allowed and what comes next.
Common misunderstanding: "A status column is the State pattern." A column is the data. The pattern is where the rules live: in one place per state (or one transition table), not in if statements scattered across controllers, jobs and views.
Definition and participants: a context (Order) holding a reference to a state object; a state interface with one method per action; concrete states implementing each action, usually by changing the context's state. A finite state machine (FSM) is the model: a set of states, events, and transitions; illegal transitions are rejected.
Order 42 (PostgreSQL, READ COMMITTED) Worker A (payment webhook) Worker B (admin cancels)
1 status = 'pending' reads pending
2 reads pending
3 UPDATE ... SET status='paid' WHERE status='pending' -> 1 row
4 UPDATE ... SET status='cancelled' WHERE status='pending' -> 0 rows
5 transition rejected: refund not needed, no lost updateReal scenario: order lifecycle (pending, paid, shipped, delivered, cancelled, refunded); subscription billing (trialing, active, past_due, cancelled); document approval (draft, in review, approved, published); a network connection (closed, listening, established); feature rollout states.
Go: state as an interface; each state type decides the transition. The lab shows the other common Go form: a transition table as data.
// Package state shows the State pattern: each order state is a type that
// knows which transitions it allows; the Order delegates to its current state.
package state
import (
"errors"
"fmt"
)
// ErrTransition is returned for an action the current state does not allow.
var ErrTransition = errors.New("transition not allowed")
// State is the behaviour that changes when the order's state changes.
type State interface {
Name() string
Pay(o *Order) error
Ship(o *Order) error
Cancel(o *Order) error
}
// Order is the context.
type Order struct {
ID string
state State
}
func New(id string) *Order { return &Order{ID: id, state: pending{}} }
func (o *Order) Status() string { return o.state.Name() }
func (o *Order) Pay() error { return o.state.Pay(o) }
func (o *Order) Ship() error { return o.state.Ship(o) }
func (o *Order) Cancel() error { return o.state.Cancel(o) }
func (o *Order) set(next State) { o.state = next }
func deny(s State, action string) error {
return fmt.Errorf("%w: %s from %s", ErrTransition, action, s.Name())
}
// Deliver and Refund follow the same shape and are omitted here; the lab
// package shows the full machine as a transition table.
type pending struct{}
func (pending) Name() string { return "pending" }
func (pending) Pay(o *Order) error { o.set(paid{}); return nil }
func (s pending) Ship(*Order) error { return deny(s, "ship") }
func (pending) Cancel(o *Order) error { o.set(cancelled{}); return nil }
type paid struct{}
func (paid) Name() string { return "paid" }
func (s paid) Pay(*Order) error { return deny(s, "pay") }
func (paid) Ship(o *Order) error { o.set(shipped{}); return nil }
func (s paid) Cancel(*Order) error { return deny(s, "cancel") } // paid orders are refunded, not cancelled
type shipped struct{}
func (shipped) Name() string { return "shipped" }
func (s shipped) Pay(*Order) error { return deny(s, "pay") }
func (s shipped) Ship(*Order) error { return deny(s, "ship") }
func (s shipped) Cancel(*Order) error { return deny(s, "cancel") }
type cancelled struct{}
func (cancelled) Name() string { return "cancelled" }
func (s cancelled) Pay(*Order) error { return deny(s, "pay") }
func (s cancelled) Ship(*Order) error { return deny(s, "ship") }
func (s cancelled) Cancel(*Order) error { return deny(s, "cancel") }Laravel: a backed enum is the state, transitions() is the machine, and Eloquent's enum cast stores it. The update is conditional on the old status, so two workers cannot both transition.
<?php
// State with a PHP 8.1+ backed enum: the enum is the state, transitions()
// is the state machine, and the model refuses illegal moves.
namespace App\Enums;
enum OrderStatus: string
{
case Pending = 'pending';
case Paid = 'paid';
case Shipped = 'shipped';
case Delivered = 'delivered';
case Cancelled = 'cancelled';
case Refunded = 'refunded';
/** @return list<self> */
public function transitions(): array
{
return match ($this) {
self::Pending => [self::Paid, self::Cancelled],
self::Paid => [self::Shipped, self::Refunded],
self::Shipped => [self::Delivered],
self::Delivered, self::Cancelled, self::Refunded => [],
};
}
public function canTransitionTo(self $next): bool
{
return in_array($next, $this->transitions(), true);
}
/** State-dependent behaviour lives on the state, not in if-chains. */
public function customerCanCancel(): bool
{
return $this === self::Pending;
}
}
namespace App\Models;
use App\Enums\OrderStatus;
use App\Events\OrderStatusChanged;
use DomainException;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = ['customer_id', 'total', 'status'];
protected function casts(): array
{
return ['status' => OrderStatus::class]; // Eloquent enum casting
}
public function transitionTo(OrderStatus $next): void
{
if (! $this->status->canTransitionTo($next)) {
throw new DomainException("Cannot move order {$this->id} from {$this->status->value} to {$next->value}");
}
$from = $this->status;
// Guard against a concurrent transition: only update if still in $from.
$updated = static::whereKey($this->id)
->where('status', $from->value)
->update(['status' => $next->value]);
if ($updated === 0) {
throw new DomainException("Order {$this->id} changed concurrently");
}
$this->status = $next;
$this->syncOriginalAttribute('status');
OrderStatusChanged::dispatch($this, $from, $next);
}
}Consequences: each state's rules in one place; illegal transitions impossible by construction; adding a state means adding a type, not editing every if. Costs: many small types for simple lifecycles; transitions spread across state classes are harder to see than a table (which is why many teams prefer the table form).
When not to use: two states and one transition (a boolean is fine); or when behaviour does not actually differ per state.
Distributed form: a saga is a state machine whose transitions are messages between services; workflow engines such as Temporal persist the state machine for you (Durable Workflows).
Related / confused with: Strategy vs State; a state machine across services is a saga.
Testing: a table test over every (from, to) pair and one test per illegal transition (order_test.go, lab_test.go); the concurrent case (two transitions from the same state) is lab experiment 6 against PostgreSQL.
Command Must-know
"Command is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations." — refactoring.guru, Command
In plain words: instead of calling charge(order) now, you write "charge order 42" on a card. The card can be run now, later, on another machine, twice for a retry, or reversed.
Common misunderstanding: "Command means CLI command." Artisan commands and Cobra commands are named after the same idea but the pattern is broader: any request as an object (a Laravel Job, an HTTP request DTO handed to a handler, an editor action with undo).
Definition and participants: a command interface (execute, optionally undo); concrete commands that hold the parameters; a receiver that does the real work; an invoker that runs commands (a button, a queue worker, a history); a client that creates commands. Because the request is data, it can be serialised, queued, logged, retried and undone.
Editor (History invoker) Undo stack Redo stack Doc.Text
1 Execute(Insert "hello") [Insert] [] "hello"
2 Execute(Replace "bye") [Insert, Replace] [] "bye"
3 Undo() [Insert] [Replace] "hello"
4 Redo() [Insert, Replace] [] "bye"
5 Execute(Insert "!") [.., Insert] [] cleared "bye!"Real scenario: queued jobs (send invoice, capture payment, resize image); undo/redo in editors; macro recording; an audit log that stores every command a user issued; retrying failed operations; scheduling (Laravel's scheduler runs jobs on a timetable: Schedule::job(new Heartbeat)->everyFiveMinutes()).
Go: commands as values with Do/Undo, a History invoker with two stacks, and the log as a by-product.
// Package command shows Command with undo/redo: every edit is an object that
// knows how to apply and revert itself, and History keeps two stacks.
package command
import "errors"
// Doc is the receiver: the thing commands act on.
type Doc struct{ Text string }
// Command is a request turned into a value.
type Command interface {
Do(d *Doc)
Undo(d *Doc)
Name() string // stored in the audit log
}
// Insert appends text at the end.
type Insert struct{ S string }
func (c Insert) Do(d *Doc) { d.Text += c.S }
func (c Insert) Undo(d *Doc) { d.Text = d.Text[:len(d.Text)-len(c.S)] }
func (c Insert) Name() string { return "insert" }
// Replace swaps the whole text; it remembers what it replaced so Undo works.
type Replace struct {
S string
old string
}
func (c *Replace) Do(d *Doc) { c.old, d.Text = d.Text, c.S }
func (c *Replace) Undo(d *Doc) { d.Text = c.old }
func (c *Replace) Name() string { return "replace" }
// ErrEmpty is returned when there is nothing to undo or redo.
var ErrEmpty = errors.New("nothing to undo or redo")
// History is the invoker: it executes commands and keeps undo/redo stacks.
type History struct {
doc *Doc
undo, redo []Command
Log []string // command history doubles as an audit log
}
func NewHistory(d *Doc) *History { return &History{doc: d} }
func (h *History) Execute(c Command) {
c.Do(h.doc)
h.undo = append(h.undo, c)
h.redo = h.redo[:0] // a new command invalidates the redo branch
h.Log = append(h.Log, "do "+c.Name())
}
func (h *History) Undo() error {
if len(h.undo) == 0 {
return ErrEmpty
}
c := h.undo[len(h.undo)-1]
h.undo = h.undo[:len(h.undo)-1]
c.Undo(h.doc)
h.redo = append(h.redo, c)
h.Log = append(h.Log, "undo "+c.Name())
return nil
}
func (h *History) Redo() error {
if len(h.redo) == 0 {
return ErrEmpty
}
c := h.redo[len(h.redo)-1]
h.redo = h.redo[:len(h.redo)-1]
c.Do(h.doc)
h.undo = append(h.undo, c)
h.Log = append(h.Log, "redo "+c.Name())
return nil
}Laravel: a queued Job is a Command: constructor parameters are the request, handle() receives the receiver by injection, the queue worker is the invoker. dispatchSync runs the same command without a queue; Bus::chain runs commands in sequence. The second half shows an undoable editor command with a persisted command log.
<?php
// Command in Laravel: a queued Job is a request turned into an object that
// can be serialized, queued, retried, chained and logged.
namespace App\Jobs;
use App\Models\Order;
use App\Services\Payments;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
final class CapturePayment implements ShouldQueue
{
use Queueable;
public int $tries = 5;
public function __construct(public Order $order) {}
/** The receiver (Payments) is injected when the worker runs the command. */
public function handle(Payments $payments): void
{
$payments->capture($this->order->id, $this->order->total, idempotencyKey: "capture-{$this->order->id}");
}
}
// Dispatch now, later, or as a chain of commands:
// CapturePayment::dispatch($order);
// CapturePayment::dispatchSync($order); // same command, no queue
// Bus::chain([new CapturePayment($order), new ShipOrder($order)])->dispatch();
namespace App\Editing;
use App\Models\Document;
use Illuminate\Support\Facades\DB;
/** An undoable command for an editor, with its history stored as rows. */
interface UndoableCommand
{
public function execute(Document $doc): void;
public function undo(Document $doc): void;
}
final class RenameDocument implements UndoableCommand
{
private ?string $previous = null;
public function __construct(private readonly string $title) {}
public function execute(Document $doc): void
{
$this->previous = $doc->title;
$doc->update(['title' => $this->title]);
}
public function undo(Document $doc): void
{
$doc->update(['title' => $this->previous]);
}
}
final class CommandHistory
{
/** @var list<UndoableCommand> */
private array $undo = [];
public function run(UndoableCommand $command, Document $doc, int $userId): void
{
DB::transaction(function () use ($command, $doc, $userId) {
$command->execute($doc);
// Audit log: every command is a row (see the command_log table on the page).
DB::table('command_log')->insert([
'document_id' => $doc->id,
'user_id' => $userId,
'command' => $command::class,
'payload' => json_encode(['title' => $doc->title]),
'created_at' => now(),
]);
});
$this->undo[] = $command;
}
public function undo(Document $doc): void
{
array_pop($this->undo)?->undo($doc);
}
}Consequences: decouples "deciding to do" from "doing"; enables queues, retries, undo, audit and replay. Costs: one class per action; undo is hard for side effects outside your control (an email cannot be unsent: you need a compensating command instead); serialised commands must stay backward-compatible while old ones sit in the queue.
When not to use: a synchronous call with no need for queuing, undo, logging or retries. A plain method call is a fine "command".
Distributed form: a message on a queue is a serialised command; idempotency keys make re-delivery safe (Idempotent Consumers, Laravel Queue Internals).
Related / confused with: Command vs Job vs Transaction Script; Memento for snapshot-based undo (Undo stacks).
Testing: run the command against a fake receiver; for undo, assert do then undo returns the original state; for jobs, Queue::fake() / Bus::fake() and Bus::assertChained (Laravel docs, Queues → Testing).
Observer Must-know
"Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing." — refactoring.guru, Observer
In plain words: "Order paid" is announced once; the email sender, the warehouse and the analytics code each listen. The order does not know who is listening.
Common misunderstanding: "Observers are asynchronous." Classic Observer is synchronous: Notify calls each observer in the subject's own thread, and a slow or throwing observer slows or breaks the subject. Laravel listeners are synchronous too unless they implement ShouldQueue.
Definition and participants: a subject (publisher) with subscribe, unsubscribe and notify; an observer (subscriber) interface; concrete observers. The subject depends only on the observer interface, so new reactions need no change to it (OCP). refactoring.guru: "You can introduce new subscriber classes without having to change the publisher’s code"
OrderService (subject) RecordStatusHistory (sync) SendPaidEmail (ShouldQueue)
1 BEGIN; status -> paid
2 dispatch OrderStatusChanged -- ShouldDispatchAfterCommit: held until commit --
3 COMMIT
4 listeners run -> INSERT order_status_history pushed to queue, returns at once
5 worker sends email later (retries on failure)Real scenario: domain events inside a monolith (order paid, user registered); cache invalidation on model save (Eloquent observers); UI data binding; webhooks fan-out; metrics and audit hooks.
Go: a typed subject with synchronous callbacks and an unsubscribe function, plus a channel fan-out where a full channel blocks the publisher (deliberate backpressure).
// Package observer shows Observer in Go: a typed, in-process subject with
// synchronous observers and an unsubscribe function, plus a channel fan-out.
package observer
import "sync"
// Subject holds observers of events of type E.
type Subject[E any] struct {
mu sync.RWMutex
next int
observers map[int]func(E)
}
// Subscribe registers fn and returns a function that removes it.
func (s *Subject[E]) Subscribe(fn func(E)) (unsubscribe func()) {
s.mu.Lock()
defer s.mu.Unlock()
if s.observers == nil {
s.observers = map[int]func(E){}
}
id := s.next
s.next++
s.observers[id] = fn
return func() {
s.mu.Lock()
delete(s.observers, id)
s.mu.Unlock()
}
}
// Notify calls every observer synchronously, in the caller's goroutine.
// Observers must be fast; slow work belongs on a queue (see Fanout).
func (s *Subject[E]) Notify(e E) {
s.mu.RLock()
fns := make([]func(E), 0, len(s.observers))
for _, fn := range s.observers {
fns = append(fns, fn)
}
s.mu.RUnlock()
for _, fn := range fns {
fn(e)
}
}
// Fanout delivers each event to every subscriber channel. A full channel
// blocks the publisher: that is backpressure, chosen on purpose here.
type Fanout[E any] struct {
mu sync.Mutex
subs []chan E
}
func (f *Fanout[E]) Subscribe(buffer int) <-chan E {
ch := make(chan E, buffer)
f.mu.Lock()
f.subs = append(f.subs, ch)
f.mu.Unlock()
return ch
}
func (f *Fanout[E]) Publish(e E) {
f.mu.Lock()
defer f.mu.Unlock()
for _, ch := range f.subs {
ch <- e
}
}
// Close ends every subscriber's range loop.
func (f *Fanout[E]) Close() {
f.mu.Lock()
defer f.mu.Unlock()
for _, ch := range f.subs {
close(ch)
}
f.subs = nil
}Laravel: event class, synchronous and queued listeners, and an Eloquent observer (registered with #[ObservedBy([ProductObserver::class])]). ShouldDispatchAfterCommit makes the event wait for the database transaction, so listeners never see an order that is then rolled back.
<?php
// Observer in Laravel: an event class, listeners that subscribe to it,
// queued listeners for slow work, and Eloquent model observers.
namespace App\Events;
use App\Enums\OrderStatus;
use App\Models\Order;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/** Listeners run only after the surrounding DB transaction commits. */
final class OrderStatusChanged implements ShouldDispatchAfterCommit
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public OrderStatus $from,
public OrderStatus $to,
) {}
}
namespace App\Listeners;
use App\Enums\OrderStatus;
use App\Events\OrderStatusChanged;
use App\Mail\OrderPaidMail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/** Queued observer: the subject does not wait for the email. */
final class SendPaidEmail implements ShouldQueue
{
public function handle(OrderStatusChanged $event): void
{
if ($event->to !== OrderStatus::Paid) {
return;
}
Mail::to($event->order->customer_email)->send(new OrderPaidMail($event->order));
}
}
/** Synchronous observer: runs in the same request (after commit), in registration order. */
final class RecordStatusHistory
{
public function handle(OrderStatusChanged $event): void
{
DB::table('order_status_history')->insert([
'order_id' => $event->order->id,
'from_status' => $event->from->value,
'to_status' => $event->to->value,
'changed_at' => now(),
]);
}
}
namespace App\Observers;
use App\Models\Product;
use Illuminate\Support\Facades\Cache;
/**
* Eloquent observer: reacts to model lifecycle events.
* Registered with #[ObservedBy([ProductObserver::class])] on the model.
*/
final class ProductObserver
{
public function saved(Product $product): void
{
Cache::forget("product:{$product->id}");
}
public function deleted(Product $product): void
{
Cache::forget("product:{$product->id}");
}
}Consequences: open for new reactions; subject decoupled from reaction code. Costs: control flow becomes invisible ("who handles this event?"); ordering between observers is implicit; an observer that throws can abort the subject's flow; observers that are never unsubscribed leak memory (the lapsed listener problem); cascades (an observer that triggers another event) are hard to reason about.
When not to use: when the subject needs a result from the reaction (that is a call, not a notification), or when there is exactly one reaction that will always exist.
Distributed form: across processes Observer becomes publish/subscribe through a broker, with durability and at-least-once delivery; see Event-Driven Architecture and the Transactional Outbox for publishing reliably after commit.
Related / confused with: Observer vs pub/sub vs Mediator.
Testing: Event::fake() then Event::assertDispatched / assertNotDispatched (Laravel docs, Events → Testing); in Go, subscribe a recording function and assert calls; test that unsubscribe works (bus_test.go).
Strategy Must-know
"Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable." — refactoring.guru, Strategy
In plain words: "how do we compute shipping?" has several answers; the checkout holds one of them and does not care which.
Common misunderstanding: "Strategy needs an interface and a class per algorithm." In Go and modern PHP a strategy is often a function: slices.SortFunc(x, cmp) takes the comparison strategy as cmp; Laravel's sortBy(fn ...) the same.
Definition and participants: a context that holds a reference to a strategy interface and delegates one task to it; concrete strategies; a client (or the container, config, a feature flag) that picks one. Strategies do not know each other.
Request Registry / container Strategy run
1 quote("weight", 2500 g) -> Registry["weight"] -> ceil(2.5) x 300 = 900
2 quote("flat", 2500 g) -> Registry["flat"] -> 500
3 feature flag free=on -> binding switches to Free -> 0 (no change to checkout code)Real scenario: shipping, tax and discount calculation; payment providers (Stripe vs PayPal); retry/backoff policies; sorting and ranking; compression or serialisation formats; authorization rules (Laravel Gates are closures and Policies are classes: two strategy shapes for "may this user do this?").
Go: the stdlib is full of strategies. sort.Sort takes a sort.Interface ("An implementation of Interface can be sorted by the routines in this package", Go docs) and the newer slices.SortFunc takes a function.
// Package strategy shows Strategy in Go: a strategy is usually just a
// function value; an interface is used when the strategy has state or
// several methods. sort.Interface and slices.SortFunc are stdlib examples.
package strategy
import (
"cmp"
"fmt"
"slices"
)
// Shipping is the strategy type: one algorithm, many interchangeable bodies.
type Shipping func(weightGrams int) (cents int64)
func Flat(weightGrams int) int64 { return 500 }
func ByWeight(perKg int64) Shipping {
return func(weightGrams int) int64 {
kg := int64((weightGrams + 999) / 1000) // round up
return kg * perKg
}
}
func Free(int) int64 { return 0 }
// Registry picks a strategy by name, e.g. from config or a feature flag.
var Registry = map[string]Shipping{
"flat": Flat,
"weight": ByWeight(300),
"free": Free,
}
// Quote is the context: it does not know which algorithm it runs.
func Quote(method string, weightGrams int) (int64, error) {
s, ok := Registry[method]
if !ok {
return 0, fmt.Errorf("unknown shipping method %q", method)
}
return s(weightGrams), nil
}
type Product struct {
Name string
Price int64
Sold int
}
// SortBy shows the stdlib's own Strategy: the comparison is passed in.
func SortBy(ps []Product, key string) {
byKey := map[string]func(a, b Product) int{
"price": func(a, b Product) int { return cmp.Compare(a.Price, b.Price) },
"popularity": func(a, b Product) int { return cmp.Compare(b.Sold, a.Sold) },
}
if f, ok := byKey[key]; ok {
slices.SortStableFunc(ps, f)
}
}Laravel: one strategy chosen by configuration through a container binding, or all strategies via tags. Laravel's container docs: "Once the services have been tagged, you may easily resolve them all via the container's tagged method"; the #[Tag('shipping')] contextual attribute injects them.
<?php
// Strategy in Laravel: an interface, interchangeable implementations, and the
// container choosing one (config) or handing you all of them (tags).
namespace App\Shipping;
interface ShippingStrategy
{
public function key(): string;
public function quote(int $grams): int; // cents
}
final class FlatRate implements ShippingStrategy
{
public function key(): string { return 'flat'; }
public function quote(int $grams): int { return 500; }
}
final class ByWeight implements ShippingStrategy
{
public function __construct(private readonly int $perKg = 300) {}
public function key(): string { return 'weight'; }
public function quote(int $grams): int { return (int) ceil($grams / 1000) * $this->perKg; }
}
final class FreeShipping implements ShippingStrategy
{
public function key(): string { return 'free'; }
public function quote(int $grams): int { return 0; }
}
namespace App\Providers;
use App\Shipping\{ByWeight, FlatRate, FreeShipping, ShippingStrategy};
use Illuminate\Support\ServiceProvider;
final class ShippingServiceProvider extends ServiceProvider
{
public function register(): void
{
// One strategy, chosen by configuration:
$this->app->bind(ShippingStrategy::class, fn () => match (config('shop.shipping')) {
'weight' => new ByWeight,
'free' => new FreeShipping,
default => new FlatRate,
});
// All strategies, so the customer can choose at checkout:
$this->app->tag([FlatRate::class, ByWeight::class, FreeShipping::class], 'shipping');
}
}
namespace App\Shipping;
use Illuminate\Container\Attributes\Tag;
use InvalidArgumentException;
/** The context: it knows the strategies only through the interface. */
final class ShippingQuoter
{
/** @param iterable<ShippingStrategy> $strategies */
public function __construct(#[Tag('shipping')] private readonly iterable $strategies) {}
public function quote(string $key, int $grams): int
{
foreach ($this->strategies as $strategy) {
if ($strategy->key() === $key) {
return $strategy->quote($grams);
}
}
throw new InvalidArgumentException("Unknown shipping method {$key}");
}
}
// Collections take strategies as closures, like Go's slices.SortFunc:
// $products->sortBy(fn ($p) => $p->price);
// Gate::define('update-post', [PostPolicy::class, 'update']); // authorization strategyConsequences: algorithms swap at runtime; each is tested alone; no switch in the context. Costs: the client must know the strategies exist to pick one; more types; overkill for two stable branches.
When not to use: the algorithm never varies, or varies only at compile time and inside one function.
Related / confused with: Strategy vs State vs Template Method. Distributed form: the choice of strategy comes from a shared feature-flag or config service so every instance agrees (Distributed data).
Testing: one table-driven test with one row per strategy and identical assertions (pricing_test.go); test the selection logic separately.
Iterator Must-know
"Iterator is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.)." — refactoring.guru, Iterator
In plain words: "give me the next one" without knowing whether the items come from a slice, a tree, a paginated API or a database cursor.
Common misunderstanding: "In Go you just use slices, so Iterator is irrelevant." Before Go 1.23 that was mostly true, and streaming code used callbacks or channels. Since Go 1.23, iter.Seq is the standard Iterator and stdlib packages (slices, maps, go/ast) return them.
Definition and participants: an iterator with "next" and "has more" (pull style) or a function that pushes each element to a callback (push style); an aggregate (collection) that creates iterators. The Go docs define the push form: "An iterator is a function that passes successive elements of a sequence to a callback function, conventionally named yield. The function stops either when the sequence is finished or when yield returns false, indicating to stop the iteration early."
for id, err := range Each(ctx, fetch) iterator body
1 fetch(cursor="") -> ids [1 2], next "p2"
2 id=1 -> loop body yield(1) true
3 id=2 -> loop body yield(2) true
4 fetch(cursor="p2") -> ids [3], next "p3"
5 id=3 -> loop body; break yield(3) false -> return, no more fetchesReal scenario: streaming a million rows to CSV without loading them; hiding pagination of a supplier API; walking a category tree; merging two sorted streams; lazily filtering logs.
Go: iter.Seq for a tree, iter.Seq2[int, error] for a paginated API that can fail, and iter.Pull to turn a push iterator into next()/stop() for a zip.
// Package iterator shows Iterator with Go 1.23 range-over-func: iter.Seq for
// a tree walk, iter.Seq2 for a paginated API that can fail, iter.Pull for a
// caller that wants to pull values one at a time.
package iterator
import (
"context"
"iter"
)
// Category is a tree; callers should not care that it is a tree.
type Category struct {
Name string
Children []*Category
}
// All yields every category depth-first. Returning false from yield stops early.
func (c *Category) All() iter.Seq[*Category] {
return func(yield func(*Category) bool) {
c.walk(yield)
}
}
func (c *Category) walk(yield func(*Category) bool) bool {
if !yield(c) {
return false
}
for _, ch := range c.Children {
if !ch.walk(yield) {
return false
}
}
return true
}
// Page is what a paginated API returns.
type Page struct {
IDs []int
Cursor string // empty when there is no next page
}
// FetchFunc loads one page; in production it is an HTTP or SQL call.
type FetchFunc func(ctx context.Context, cursor string) (Page, error)
// Each hides pagination: the caller ranges over ids and sees errors inline.
func Each(ctx context.Context, fetch FetchFunc) iter.Seq2[int, error] {
return func(yield func(int, error) bool) {
cursor := ""
for {
p, err := fetch(ctx, cursor)
if err != nil {
yield(0, err)
return
}
for _, id := range p.IDs {
if !yield(id, nil) {
return
}
}
if p.Cursor == "" {
return
}
cursor = p.Cursor
}
}
}
// Zip merges two sequences pairwise using pull iterators.
func Zip[A, B any](as iter.Seq[A], bs iter.Seq[B]) iter.Seq2[A, B] {
return func(yield func(A, B) bool) {
nextA, stopA := iter.Pull(as)
defer stopA()
nextB, stopB := iter.Pull(bs)
defer stopB()
for {
a, okA := nextA()
b, okB := nextB()
if !okA || !okB || !yield(a, b) {
return
}
}
}
}Laravel: a generator behind IteratorAggregate, and LazyCollection::make around a paginated API. Laravel's docs: "the LazyCollection class leverages PHP's generators to allow you to work with very large datasets while keeping memory usage low." Eloquent's lazy() (chunked queries) and cursor() (one query, one hydrated model at a time) are iterators over tables.
<?php
// Iterator in PHP/Laravel: generators, IteratorAggregate, and LazyCollection,
// which wraps a generator so you can stream rows or API pages with low memory.
namespace App\Catalog;
use Generator;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\LazyCollection;
use IteratorAggregate;
use Traversable;
/** A collection type that hides its storage: callers just foreach it. */
final class CategoryTree implements IteratorAggregate
{
/** @param list<CategoryTree> $children */
public function __construct(public readonly string $name, private array $children = []) {}
public function getIterator(): Traversable
{
return $this->walk();
}
private function walk(): Generator
{
yield $this;
foreach ($this->children as $child) {
yield from $child->walk();
}
}
}
final class SupplierCatalog
{
/** Hides cursor pagination: the caller sees one lazy stream of products. */
public function products(): LazyCollection
{
return LazyCollection::make(function () {
$cursor = null;
do {
$page = Http::get('https://supplier.example/api/products', ['cursor' => $cursor])->throw()->json();
foreach ($page['data'] as $product) {
yield $product;
}
$cursor = $page['next_cursor'] ?? null;
} while ($cursor !== null);
});
}
}
// Usage: only as many pages are fetched as take() needs.
// $cheap = app(SupplierCatalog::class)->products()
// ->filter(fn ($p) => $p['price'] < 1000)
// ->take(50)
// ->all();
//
// Eloquent iterators over large tables:
// foreach (Order::where('status', 'paid')->lazy() as $order) { ... } // chunked queries
// foreach (Order::cursor() as $order) { ... } // one query, one row hydrated at a timeConsequences: callers are independent of storage; memory stays flat; early stop is free. Costs: a lazy iterator holds resources (an open cursor, an HTTP page) while the caller is slow; errors surface mid-loop, not up front; iterating twice may re-run the work (Laravel's remember() caches already enumerated values).
When not to use: small in-memory collections where a slice or array is simpler and faster.
Related / confused with: Iterator decides order, Visitor decides the operation per type; Composite trees are usually walked with an iterator (Structural Patterns). Distributed form: cursor or keyset pagination over an API (Pagination), and a consumer reading a stream partition offset by offset.
Testing: assert the sequence, early stop (break after N), and that errors are yielded (iterator_test.go).
Mediator Important
"Mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object." — refactoring.guru, Mediator
In plain words: planes do not talk to each other, they talk to the tower. The tower owns the rules.
Common misunderstanding: "An event bus is a Mediator, so any event bus fixes coupling." A generic bus only routes; the coupling rules still live in the listeners. A Mediator in the GoF sense contains the coordination logic. If the "who reacts to whom" rules are scattered over twenty listeners, you have Observer, not Mediator.
Definition and participants: a mediator interface; a concrete mediator that knows all colleagues and encodes how they interact; colleagues that know only the mediator. With n colleagues, direct links grow as n(n−1)/2; with a mediator they are n.
Colleague Mediator (Checkout) Effect
1 Coupon applied -> Changed("coupon") recalculate()
2 total 6000 -> 4800 (below 5000) shipping 0 -> 500
3 Summary.Payable = 5300 Cart, Coupon, Summary never call each otherReal scenario: a checkout form where coupon, country and cart affect each other; a chat room; air-traffic-style resource allocation; a module coordinator in a modular monolith (a use case that calls inventory, billing and notifications in order); UI dialogs with dependent fields.
Go: a coordinator struct; and the goroutine form, where one goroutine owns the state and colleagues send it commands over a channel (no locks, all rules in one loop).
// Package mediator shows Mediator: colleagues never call each other; they
// tell the mediator what happened and it decides who reacts.
package mediator
// Colleagues of a checkout form.
type Cart struct{ Total int64 }
type Coupon struct {
Code string
Percent int64
}
type ShippingForm struct{ Country string }
type Summary struct{ Payable, Shipping int64 }
// Checkout is the mediator. Every interaction rule lives here, not in the parts.
type Checkout struct {
Cart *Cart
Coupon *Coupon
Shipping *ShippingForm
Summary *Summary
}
// Changed is the single entry point colleagues use.
func (m *Checkout) Changed(source string) {
switch source {
case "cart", "coupon", "country":
m.recalculate()
}
}
func (m *Checkout) recalculate() {
total := m.Cart.Total
if m.Coupon != nil && m.Coupon.Code != "" {
total -= total * m.Coupon.Percent / 100
}
var ship int64
switch {
case m.Shipping.Country != "DE":
ship = 1_500 // international
case total < 5_000:
ship = 500 // domestic, below the free-shipping threshold
}
m.Summary.Shipping = ship
m.Summary.Payable = total + ship
}
// Command is what goroutine colleagues send to a channel-based mediator.
type Command struct {
Source string
Apply func(*Checkout)
Done chan Summary
}
// Run owns the Checkout; only this goroutine touches it, so no locks.
func Run(m *Checkout, in <-chan Command) {
for c := range in {
c.Apply(m)
m.Changed(c.Source)
c.Done <- *m.Summary
}
}Laravel: a coordinator class (an Action) that owns the interaction between modules; the event dispatcher is the generic mediator between publishers and listeners.
<?php
// Mediator: modules do not call each other; a coordinator owns the interaction.
// Laravel's event dispatcher is a generic mediator between publishers and listeners.
namespace App\Checkout;
use App\Billing\BillingModule;
use App\Inventory\InventoryModule;
use App\Notifications\NotificationModule;
use Illuminate\Support\Facades\DB;
/**
* Without a mediator, Inventory calls Billing which calls Notifications:
* every module knows two others. Here each module knows only the mediator's
* call into it, and the order of interaction is in one readable place.
*/
final class CheckoutMediator
{
public function __construct(
private readonly InventoryModule $inventory,
private readonly BillingModule $billing,
private readonly NotificationModule $notifications,
) {}
public function placeOrder(int $customerId, array $lines): int
{
return DB::transaction(function () use ($customerId, $lines) {
$reservationId = $this->inventory->reserve($lines);
$orderId = $this->billing->createInvoice($customerId, $lines, $reservationId);
$this->notifications->orderPlaced($customerId, $orderId); // queued inside the module
return $orderId;
});
}
}
// The dispatcher as mediator: a module announces, it does not address anyone.
// event(new \App\Events\OrderPlaced($orderId));
// Event::listen(\App\Events\OrderPlaced::class, [\App\Inventory\Listeners\Commit::class, 'handle']);Consequences: colleagues become reusable and simple; the interaction is readable in one place. Costs: the mediator can grow into a god object (split per use case); everything depends on it.
When not to use: two or three colleagues with one interaction; or when announcements with independent reactions are enough (Observer).
Distributed form: saga orchestration is a mediator across services; a Process Manager in EIP terms.
Related / confused with: Observer vs pub/sub vs Mediator; Facade simplifies access to a subsystem, a Mediator coordinates peers (Structural Patterns).
Testing: drive colleagues through the mediator and assert final state; for the channel form, send commands and read replies, no sleeps (checkout_test.go).
Memento Good to know
"Memento is a behavioral design pattern that lets you save and restore the previous state of an object without revealing the details of its implementation." — refactoring.guru, Memento
In plain words: take a sealed snapshot you can hand back later to restore, without anyone else reading what is inside.
Common misunderstanding: "Memento is just serialising the object to JSON." Serialising is the mechanism. The pattern is about who may read the snapshot: only the originator. A caretaker (undo stack, versions table) stores it but must not depend on its fields, so the originator's internals can change.
Definition and participants: an originator that creates and restores mementos; a memento (opaque state plus metadata such as timestamp); a caretaker that keeps mementos (stack, ring buffer, table). refactoring.guru notes the link to Command: "commands are responsible for performing various operations over a target object, while mementos save the state of that object just before a command gets executed."
User Document (originator) document_versions (caretaker)
1 edit title snapshot() -> v1 {title:A} INSERT v1
2 edit body snapshot() -> v2 {title:B} INSERT v2
3 "restore v1" snapshot() -> v3 (current) INSERT v3 (restore is undoable)
4 fill(v1.state); save() title = A againReal scenario: undo in editors and settings screens; document/page version history (wikis, CMS); "draft" vs "published" copies; game save points; rolling back a failed multi-step configuration change.
Go: unexported fields make the memento opaque outside the package; the caretaker is bounded because memory is the main cost.
// Package memento shows Memento: the originator exports an opaque snapshot,
// a caretaker stores snapshots, and only the originator can read them.
package memento
import "time"
// Settings is the originator. Its fields stay unexported.
type Settings struct {
theme string
fontSize int
}
func (s *Settings) SetTheme(t string) { s.theme = t }
func (s *Settings) SetFontSize(n int) { s.fontSize = n }
func (s *Settings) Theme() string { return s.theme }
func (s *Settings) FontSize() int { return s.fontSize }
// Snapshot is the memento. Outside this package it is opaque: callers can
// store and pass it, but cannot read or change theme or fontSize.
type Snapshot struct {
theme string
fontSize int
At time.Time // metadata is fine to expose
}
func (s *Settings) Save(now time.Time) Snapshot {
return Snapshot{theme: s.theme, fontSize: s.fontSize, At: now}
}
func (s *Settings) Restore(m Snapshot) {
s.theme, s.fontSize = m.theme, m.fontSize
}
// Caretaker keeps a bounded history; it never looks inside a Snapshot.
type Caretaker struct {
Max int
saved []Snapshot
}
func (c *Caretaker) Push(m Snapshot) {
c.saved = append(c.saved, m)
if c.Max > 0 && len(c.saved) > c.Max {
c.saved = c.saved[1:] // drop the oldest: memory is the main cost
}
}
func (c *Caretaker) Pop() (Snapshot, bool) {
if len(c.saved) == 0 {
return Snapshot{}, false
}
m := c.saved[len(c.saved)-1]
c.saved = c.saved[:len(c.saved)-1]
return m, true
}Laravel: snapshots in a versions table (schema in Mechanics); restore is itself snapshotted so it can be undone.
<?php
// Memento in Laravel: snapshots of a model stored in a versions table.
// The model creates and restores snapshots; the table (caretaker) only stores them.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;
class Document extends Model
{
protected $fillable = ['title', 'body', 'settings'];
protected function casts(): array
{
return ['settings' => 'array'];
}
public function versions(): HasMany
{
return $this->hasMany(DocumentVersion::class);
}
/** Originator: decides what goes into the memento. */
public function snapshot(int $userId): DocumentVersion
{
return $this->versions()->create([
'user_id' => $userId,
'version' => ($this->versions()->max('version') ?? 0) + 1,
'state' => $this->only(['title', 'body', 'settings']),
]);
}
/** Originator: the only code that interprets a memento's contents. */
public function restore(DocumentVersion $version, int $userId): void
{
DB::transaction(function () use ($version, $userId) {
$this->snapshot($userId); // restoring is itself undoable
$this->fill($version->state)->save();
});
}
}
class DocumentVersion extends Model
{
public const UPDATED_AT = null; // versions are immutable
protected $fillable = ['user_id', 'version', 'state'];
protected function casts(): array
{
return ['state' => 'array'];
}
}Consequences: encapsulation preserved; simple, robust undo. Costs: memory/storage per snapshot (store diffs or cap history); snapshots of objects with external links (files, foreign keys) may restore inconsistently.
When not to use: large objects edited in tiny steps (prefer Command undo or diffs); or when you need why something changed (that is an event log, see Event Sourcing).
Related / confused with: Command undo vs Memento undo; Prototype (a copy) can replace Memento for simple objects (Creational Patterns). Distributed form: snapshots in an event-sourced store.
Testing: save, mutate, restore, assert equality; assert bounded history drops the oldest (editor_test.go).
Visitor Important
"Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate." — refactoring.guru, Visitor
In plain words: you have a fixed set of node types (product line, shipping line, discount line) and keep inventing new operations over them (tax, CSV, PDF). Each operation becomes one visitor class instead of a method added to every node type.
Common misunderstanding: "Visitor makes adding anything easy." It makes adding operations easy and adding types hard: a new node type means a new method on every visitor. That is the expression problem, and Visitor picks one side of it.
Definition and participants: an element interface with accept(visitor); concrete elements that call the visitor method for their own type (visitor.visitProduct(this)); a visitor interface with one method per element type; concrete visitors per operation. The two calls (accept picks the element, visitX picks the operation) are double dispatch; refactoring.guru: "It uses a technique called Double Dispatch, which helps to execute the proper method on an object without cumbersome conditionals."
Apply(items, vat)
1 ProductLine.accept(vat) -> vat.visitProduct(p) tax += 190
2 ShippingLine.accept(vat) -> vat.visitShipping(s) tax += 95
3 DiscountLine.accept(vat) -> vat.visitDiscount(d) tax -= 19 => 266
4 same items, Lines visitor -> three CSV rows, items unchangedReal scenario: compilers and linters walking an AST (Go's go/ast, PHP-Parser's node visitors, ESLint rules); exporting a document model to several formats; computing metrics over a fixed domain tree; tax and reporting over invoice lines.
Go: classic double dispatch, and the stdlib Visitor. The Go docs: "A Visitor's Visit method is invoked for each node encountered by Walk"; ast.Inspect is the same traversal with a closure, and Go 1.23 added ast.Preorder, which "returns an iterator over all the nodes of the syntax tree".
// Package visitor shows Visitor two ways: classic double dispatch over a
// closed set of line-item types, and the stdlib's go/ast Walk and Inspect.
package visitor
import (
"go/ast"
"go/parser"
"go/token"
)
// Item is the element interface: every item accepts a visitor.
type Item interface{ Accept(v Visitor) }
type Product struct {
SKU string
Cents int64
}
type Shipping struct{ Cents int64 }
type Discount struct{ Cents int64 }
// Double dispatch: the item picks the visitor method by its own type.
func (p Product) Accept(v Visitor) { v.VisitProduct(p) }
func (s Shipping) Accept(v Visitor) { v.VisitShipping(s) }
func (d Discount) Accept(v Visitor) { v.VisitDiscount(d) }
// Visitor is one operation over all item types. New operation = new visitor;
// new item type = edit every visitor (the trade-off).
type Visitor interface {
VisitProduct(Product)
VisitShipping(Shipping)
VisitDiscount(Discount)
}
// VAT computes tax: products 19%, shipping 19%, discounts reduce the base.
type VAT struct{ Cents int64 }
func (t *VAT) VisitProduct(p Product) { t.Cents += p.Cents * 19 / 100 }
func (t *VAT) VisitShipping(s Shipping) { t.Cents += s.Cents * 19 / 100 }
func (t *VAT) VisitDiscount(d Discount) { t.Cents -= d.Cents * 19 / 100 }
// Lines renders an invoice: a second operation, no change to the items.
type Lines struct{ Out []string }
func (l *Lines) VisitProduct(p Product) { l.Out = append(l.Out, "product "+p.SKU) }
func (l *Lines) VisitShipping(Shipping) { l.Out = append(l.Out, "shipping") }
func (l *Lines) VisitDiscount(Discount) { l.Out = append(l.Out, "discount") }
func Apply(items []Item, v Visitor) {
for _, it := range items {
it.Accept(v)
}
}
// CountFuncs uses ast.Inspect: a visitor written as a closure.
func CountFuncs(src string) (int, error) {
f, err := parser.ParseFile(token.NewFileSet(), "x.go", src, 0)
if err != nil {
return 0, err
}
n := 0
ast.Inspect(f, func(node ast.Node) bool {
if _, ok := node.(*ast.FuncDecl); ok {
n++
}
return true // keep descending
})
return n, nil
}
// callCounter implements ast.Visitor for ast.Walk.
type callCounter struct{ calls map[string]int }
func (c callCounter) Visit(node ast.Node) ast.Visitor {
if call, ok := node.(*ast.CallExpr); ok {
if id, ok := call.Fun.(*ast.Ident); ok {
c.calls[id.Name]++
}
}
return c
}
// CountCalls returns how often each plain function name is called.
func CountCalls(src string) (map[string]int, error) {
f, err := parser.ParseFile(token.NewFileSet(), "x.go", src, 0)
if err != nil {
return nil, err
}
c := callCounter{calls: map[string]int{}}
ast.Walk(c, f)
return c.calls, nil
}Laravel / PHP: double dispatch over readonly line classes; a match (true) with instanceof is the lighter alternative for small closed sets.
<?php
// Visitor in PHP: double dispatch over a closed set of invoice line types.
// Adding an operation = a new visitor class; adding a line type = edit all visitors.
namespace App\Invoicing;
interface LineVisitor
{
public function visitProduct(ProductLine $line): void;
public function visitShipping(ShippingLine $line): void;
public function visitDiscount(DiscountLine $line): void;
}
interface Line
{
public function accept(LineVisitor $visitor): void;
}
final readonly class ProductLine implements Line
{
public function __construct(public string $sku, public int $cents) {}
public function accept(LineVisitor $visitor): void { $visitor->visitProduct($this); }
}
final readonly class ShippingLine implements Line
{
public function __construct(public int $cents) {}
public function accept(LineVisitor $visitor): void { $visitor->visitShipping($this); }
}
final readonly class DiscountLine implements Line
{
public function __construct(public int $cents) {}
public function accept(LineVisitor $visitor): void { $visitor->visitDiscount($this); }
}
final class VatVisitor implements LineVisitor
{
public int $cents = 0;
public function visitProduct(ProductLine $line): void { $this->cents += intdiv($line->cents * 19, 100); }
public function visitShipping(ShippingLine $line): void { $this->cents += intdiv($line->cents * 19, 100); }
public function visitDiscount(DiscountLine $line): void { $this->cents -= intdiv($line->cents * 19, 100); }
}
final class CsvRowsVisitor implements LineVisitor
{
/** @var list<array> */
public array $rows = [];
public function visitProduct(ProductLine $line): void { $this->rows[] = ['product', $line->sku, $line->cents]; }
public function visitShipping(ShippingLine $line): void { $this->rows[] = ['shipping', '', $line->cents]; }
public function visitDiscount(DiscountLine $line): void { $this->rows[] = ['discount', '', -$line->cents]; }
}
// PHP 8 alternative when the set of types is closed and small: a match on the class.
// $vat = fn (Line $l) => match (true) {
// $l instanceof ProductLine, $l instanceof ShippingLine => intdiv($l->cents * 19, 100),
// $l instanceof DiscountLine => -intdiv($l->cents * 19, 100),
// };Consequences: new operations without touching element classes; related behaviour grouped per visitor. Costs: new element types touch every visitor; visitors often need access to element internals (public fields or getters); the accept/visit indirection confuses readers. In Go a type switch (switch n := node.(type)) is often clearer.
When not to use: element types change often; only one or two operations exist.
Related / confused with: Iterator (order) vs Visitor (operation); a type switch is the lightweight alternative (Single vs double dispatch). No distributed form: across services each consumer simply implements its own handling per event type.
Testing: run each visitor over a fixed list of elements and assert the result; for go/ast, parse a small source string and assert counts (visitor_test.go).
Interpreter Good to know
In plain words: for a tiny language (discount rules, search filters, feature-flag conditions) make one class per grammar rule, build a tree from the sentence, and evaluate the tree.
Common misunderstanding: "Interpreter is how you build a programming language." For anything beyond a small grammar you use a parser generator or a real expression engine. The GoF Interpreter is for small, stable grammars where a tree of objects is clear enough. Wikipedia summarises the structure: "Represent a sentence in the language by an abstract syntax tree (AST) made up of Expression instances" and notes the tree is a Composite.
Definition and participants: abstract expression (Eval/evaluate); terminal expressions (comparisons, literals); nonterminal expressions (and, or) holding sub-expressions; a context (the facts); a client or parser that builds the tree. Visitor is the usual way to add operations other than evaluation (pretty-printing, validation).
Rule JSON: all[ total>=10000, any[ tier==gold, orders>=20 ] ]
1 RuleParser::parse -> AllOf(AtLeast, AnyOf(Equals, AtLeast))
2 evaluate({total:12000, tier:gold}) -> AtLeast true -> AnyOf: Equals true -> true
3 admin edits the JSON in a UI; no deploy needed for a new ruleReal scenario: promotion and pricing rules edited by business users; access rules (attribute-based conditions); search filter DSLs; alerting conditions.
// Package interpreter shows Interpreter: a tiny rule language for discounts.
// Each grammar rule is a type; the sentence is a tree; Eval interprets it.
//
// expr := cmp | expr "and" expr | expr "or" expr
// cmp := field (">=" | "==") value
package interpreter
// Facts are the input the rules are evaluated against.
type Facts map[string]int64
// Expr is the abstract expression.
type Expr interface{ Eval(f Facts) bool }
// Terminal expressions.
type AtLeast struct {
Field string
Min int64
}
func (e AtLeast) Eval(f Facts) bool { return f[e.Field] >= e.Min }
type Equals struct {
Field string
Want int64
}
func (e Equals) Eval(f Facts) bool { return f[e.Field] == e.Want }
// Nonterminal expressions: they hold sub-expressions (a Composite).
type And struct{ L, R Expr }
func (e And) Eval(f Facts) bool { return e.L.Eval(f) && e.R.Eval(f) }
type Or struct{ L, R Expr }
func (e Or) Eval(f Facts) bool { return e.L.Eval(f) || e.R.Eval(f) }
// VIPRule is the sentence: total >= 10000 and (tier == 2 or orders >= 20).
var VIPRule Expr = And{
L: AtLeast{"total", 10_000},
R: Or{Equals{"tier", 2}, AtLeast{"orders", 20}},
}<?php
// Interpreter: a tiny discount-rule language stored as JSON and evaluated
// as a tree of expression objects (each grammar rule is a class).
namespace App\Rules;
use InvalidArgumentException;
interface Expr
{
public function evaluate(array $facts): bool;
}
final readonly class AtLeast implements Expr
{
public function __construct(private string $field, private int $min) {}
public function evaluate(array $facts): bool { return ($facts[$this->field] ?? 0) >= $this->min; }
}
final readonly class Equals implements Expr
{
public function __construct(private string $field, private int|string $value) {}
public function evaluate(array $facts): bool { return ($facts[$this->field] ?? null) === $this->value; }
}
final readonly class AllOf implements Expr
{
/** @param list<Expr> $parts */
public function __construct(private array $parts) {}
public function evaluate(array $facts): bool
{
foreach ($this->parts as $p) {
if (! $p->evaluate($facts)) {
return false;
}
}
return true;
}
}
final readonly class AnyOf implements Expr
{
/** @param list<Expr> $parts */
public function __construct(private array $parts) {}
public function evaluate(array $facts): bool
{
foreach ($this->parts as $p) {
if ($p->evaluate($facts)) {
return true;
}
}
return false;
}
}
/** Parser: JSON stored by an admin UI -> expression tree. */
final class RuleParser
{
public static function parse(array $node): Expr
{
return match ($node['op']) {
'gte' => new AtLeast($node['field'], (int) $node['value']),
'eq' => new Equals($node['field'], $node['value']),
'all' => new AllOf(array_map(self::parse(...), $node['of'])),
'any' => new AnyOf(array_map(self::parse(...), $node['of'])),
default => throw new InvalidArgumentException("Unknown op {$node['op']}"),
};
}
}
// RuleParser::parse(['op' => 'all', 'of' => [
// ['op' => 'gte', 'field' => 'total', 'value' => 10000],
// ['op' => 'any', 'of' => [['op' => 'eq', 'field' => 'tier', 'value' => 'gold'], ['op' => 'gte', 'field' => 'orders', 'value' => 20]]],
// ]])->evaluate(['total' => 12000, 'tier' => 'gold']); // trueWhen not to use: large grammars, performance-critical evaluation, or when an existing engine (SQL WHERE, CEL, JSON Logic, a search engine query) already covers it. Store rules as data, validate them on save, and version them.
Related / confused with: the tree is a Composite (Structural Patterns); Visitor adds operations to it. Testing: a truth table of facts → expected result per rule (rules_test.go).
Per-language view
Which built-in feature already is the pattern, so you do not re-implement it.
| Pattern | Go stdlib / idiom | PHP / Laravel 13 | Java / Spring | JavaScript / TypeScript |
|---|---|---|---|---|
| Template Method | Function + interface of steps | Abstract class, final method; PHPUnit setUp | AbstractController, JdbcTemplate callbacks | Base class or higher-order function |
| Chain of Responsibility | func(http.Handler) http.Handler | Middleware, Pipeline facade | Servlet Filter chain, Spring Security filter chain | Express/Koa middleware |
| State | Interface per state or transition map | Backed enum + Eloquent enum cast | Spring Statemachine | XState |
| Command | Value with Do/Undo; closures | Jobs (ShouldQueue), Bus::chain, Artisan commands, scheduler | Runnable, @Async | Redux actions |
| Observer | Callbacks, channels; context.AfterFunc | Events/listeners, Eloquent observers | ApplicationEventPublisher, @EventListener | EventTarget, RxJS |
| Strategy | func values, sort.Interface, slices.SortFunc | Interface + binding; container tag/tagged; Gates and Policies | Interface + @Qualifier | Functions as values |
| Iterator | iter.Seq, iter.Seq2, iter.Pull | Iterator, IteratorAggregate, generators, LazyCollection | Iterator, Stream | Symbol.iterator, generators |
| Mediator | Coordinator struct; goroutine owning state | Action/coordinator; event dispatcher | MediatR-style libraries are .NET; Spring uses services | Redux store as mediator |
| Memento | Struct with unexported fields | Versions table, $model->replicate() copies | Serializable snapshots | Immutable state snapshots |
| Visitor | ast.Walk, ast.Inspect, ast.Preorder, type switch | accept/visit, PHP-Parser NodeVisitor | FileVisitor (Files.walkFileTree) | Babel/ESLint visitors |
| Interpreter | Expr interface; text/template/parse builds a tree | Rule classes; Blade compiles, it does not interpret | SpEL | JSON Logic |
Go's context.Context is two patterns at once. Its Done() channel is an observer hook ("Done returns a channel that's closed when work done on behalf of this context should be canceled", Go docs) and cancellation propagates down a chain of derived contexts; context.AfterFunc "arranges to call f in its own goroutine after ctx is canceled", which is a registered observer.
Laravel's Macroable is not a behavioral pattern. Collection::macro('toUpper', fn ...) adds a method at runtime (Laravel docs: “Collections are "macroable"”). It is an extension mechanism (closer to GoF's later "extension object" idea); use it for small helpers, not to inject per-request behaviour, which is what Strategy is for.
Mechanics
Single vs double dispatch Important
Go, PHP and Java choose the method to run by the receiver's runtime type only (single dispatch). vat.visit(item) cannot pick visitProduct vs visitShipping by the argument's runtime type; overloads (where they exist) are chosen at compile time. Visitor adds a second dispatch: item.accept(v) dispatches on the item, which then calls v.visitProduct(this), dispatching on the visitor. Alternatives: Go's type switch, PHP's match (true) with instanceof; both are fine for closed, small sets and give up the compile-time check that every visitor handles every type.
Push vs pull iterators Must-know
| Style | Who controls the loop | Go | PHP | Typical use |
|---|---|---|---|---|
| Push | The iterator calls you | iter.Seq[V]: func(yield func(V) bool) | foreach over a generator (looks pull, runs as coroutine) | Range loops, streaming |
| Pull | You call next() | iter.Pull(seq) returns next, stop | Iterator::current()/next()/valid() | Zip, merge, parsers |
| Channel | Producer goroutine sends | chan T + goroutine | n/a | Concurrent producers; costs a goroutine and needs cancellation |
The Go docs say "The standard iterators can be thought of as" push iterators, and that Pull "converts a standard push iterator to a" pull iterator. Always call stop (use defer), or the iterator's goroutine-like state leaks. A push iterator must honour yield returning false; ignoring it panics at runtime when the loop has exited.
Synchronous vs queued notification Must-know
| Question | Synchronous observer | Queued listener (ShouldQueue) | Broker pub/sub |
|---|---|---|---|
| Runs in | Subject's thread/request | Queue worker | Consumer service |
| Subject waits | Yes | No (only the push) | No |
| Observer throws | Exception reaches the subject | Retried by the worker, then failed_jobs | Retried, then DLQ |
| Same DB transaction | Yes (can roll back together) | No | No |
| Survives crash | No | Yes once pushed | Yes once acknowledged |
| Ordering | Registration order | Per queue, not guaranteed across workers | Per partition/queue |
Two traps: dispatching inside a transaction that later rolls back (fix: ShouldDispatchAfterCommit on the event, or record events on the aggregate and publish after commit as the Go lab does); and an observer that loads the whole world synchronously (move it to a queue).
Undo stacks: Command vs Memento Important
| Command undo | Memento undo | |
|---|---|---|
| Stores | How to reverse (inverse op + minimal old value) | A full (or diff) snapshot before the change |
| Memory | Small | Large for big objects |
| Works for | Reversible operations | Any change, including complex ones |
| Fails for | Side effects outside your control (email, payment) | External links (files, other tables) |
| Redo | Re-execute the command | Keep the "after" snapshot too |
Rules for both: a new action clears the redo stack; cap history (count or bytes); persist only what you must. The persisted forms:
-- PostgreSQL: command history as an audit log (Command)
CREATE TABLE command_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
document_id bigint NOT NULL REFERENCES documents(id),
user_id bigint NOT NULL,
command text NOT NULL, -- e.g. App\Editing\RenameDocument
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON command_log (document_id, id);
-- Snapshots (Memento): one row per version, immutable
CREATE TABLE document_versions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
document_id bigint NOT NULL REFERENCES documents(id),
version int NOT NULL,
user_id bigint NOT NULL,
state jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (document_id, version)
);The UNIQUE (document_id, version) constraint turns two concurrent snapshots computing the same max(version) + 1 into a unique-violation error (PostgreSQL SQLSTATE 23505, MySQL error 1062) instead of a silent duplicate; retry on it.
Transition tables and persisted state machines Must-know
A State pattern in memory is not enough once two processes can touch the same order. The database must enforce the same machine:
-- PostgreSQL: allowed transitions as data, checked by the UPDATE below
CREATE TABLE order_transitions (
from_status text NOT NULL,
to_status text NOT NULL,
PRIMARY KEY (from_status, to_status)
);
INSERT INTO order_transitions VALUES
('pending','paid'), ('pending','cancelled'),
('paid','shipped'), ('paid','refunded'), ('shipped','delivered');
ALTER TABLE orders ADD CONSTRAINT orders_status_check
CHECK (status IN ('pending','paid','shipped','delivered','cancelled','refunded'));
-- Compare-and-set transition: succeeds for exactly one concurrent caller
UPDATE orders SET status = 'paid', updated_at = now()
WHERE id = 42 AND status = 'pending'
AND EXISTS (SELECT 1 FROM order_transitions WHERE from_status = 'pending' AND to_status = 'paid');
-- 1 row: you won. 0 rows: someone else moved it, or the move is illegal.
-- History table written by the transition (Observer in SQL form)
CREATE TABLE order_status_history (
order_id bigint NOT NULL, from_status text NOT NULL, to_status text NOT NULL,
changed_at timestamptz NOT NULL DEFAULT now()
);The conditional UPDATE ... WHERE status = 'pending' is optimistic concurrency on the state itself; see Optimistic vs Pessimistic Locking. MySQL InnoDB behaves the same way for this statement (the row lock taken by the first UPDATE makes the second re-check the condition after the first commits). CHECK constraints are enforced in PostgreSQL and in MySQL from 8.0.16.
Middleware ordering: the onion Important
Chain(final, Logging, RequireToken, RateLimit)
1 Logging before -> calls next
2 RequireToken before -> calls next
3 RateLimit before -> calls next
4 final handler
5 RateLimit after
6 RequireToken after
7 Logging after (sees status code, duration)The first middleware listed is the outermost layer: it runs first on the way in and last on the way out. In Go the Chain helper builds the onion by wrapping from the end; in Laravel the order is the middleware array order (with the global stack outside route middleware). Put recovery and tracing outermost, auth before anything that touches data, and rate limiting before expensive work.
Pipeline vs middleware in Laravel Good to know
Pipeline::send($input)->through([...])->then($destination) runs any object through invokable classes or closures; each receives the input and $next. Class names are resolved through the container ("If a class name is provided, the class will be instantiated via Laravel's service container", Laravel docs), so pipes get dependencies injected. thenReturn() returns the input after the last pipe. Use it for checkout steps, import steps, query filters; keep HTTP concerns in middleware.
Testing each pattern
| Pattern | What to assert | Go tool | Laravel tool |
|---|---|---|---|
| Template Method | Step order; each variant's output | Fake Steps, strings.Builder | Plain unit test on subclass |
| Chain | Stops when it should; order; next called once | httptest.NewRecorder, fake next | $this->get() feature test; call middleware handle with a closure |
| State | Every legal and illegal transition; concurrent transition | Table test over pairs | Enum unit test; DB test for conditional update |
| Command | do then undo restores; serialisation; idempotency | Fake receiver | Queue::fake(), Bus::fake(), Bus::assertChained |
| Observer | Dispatched or not; listener effect alone | Recording callback | Event::fake(), Event::assertDispatched, assertNotDispatched |
| Strategy | Same contract for every implementation | Table-driven, one row per strategy | Data provider over tagged services |
| Iterator | Sequence, early stop, error mid-stream | slices.Collect, break in loop | LazyCollection with a fake HTTP (Http::fake) |
| Mediator | Final state after colleague events | Channel request/reply, no sleeps | Mock modules, assert call order |
| Memento | Restore equals saved; bounded history | Unexported fields still compared via getters | DB test on versions table |
| Visitor | Each visitor over a fixed element list | Parse source string for go/ast | Unit test per visitor |
| Interpreter | Truth table of the rule | Table test of facts | Parser + evaluate tests |
Run the Go suite with the race detector: go test -race ./... from docs/snippets/design/behavioral-patterns/go (all eleven packages and the lab pass).
Solving the classic problems
| Problem | Pattern(s) | How | Advantage | Cost / limitation |
|---|---|---|---|---|
Order status ifs everywhere | State (+ transition table) | Enum/state type owns transitions; conditional UPDATE | One place for rules; no illegal states | Table and code must stay in sync |
| Fat checkout controller | Chain (Pipeline) + Command | One pipe per step; a job per side effect | Steps reorderable and testable | Flow spread over files |
| Purchase approvals by amount | Chain of Responsibility | Links ordered by limit; explicit "no approver" error | New level = new link | Rules hidden in order |
| Undo/redo in an editor | Command (+ Memento for complex edits) | Two stacks; snapshot before risky commands | Small memory, precise undo | Irreversible side effects need compensation |
| Audit log of user actions | Command | Persist each command with user and payload | Replay and forensics | Schema of old commands must stay readable |
| Modules reacting to each other | Observer (in-process) or Mediator | Events for independent reactions; coordinator for ordered ones | Low coupling | Invisible flow; ordering |
switch ($method) for pricing/shipping | Strategy | Interface + registry/container tags | New method without editing checkout | Selection logic still needed |
| Export of millions of rows | Iterator | LazyCollection, lazy(), iter.Seq | Flat memory | Long-held cursor/connection |
| Many reports over one domain tree | Visitor | One visitor per report | Reports added freely | New node type edits all visitors |
| Business-editable rules | Interpreter | Rules as JSON → expression tree | No deploy per rule | Validation, versioning, testing of rules |
Order workflow
Use an enum (Laravel) or a transition map (Go) as the single source of allowed moves, a conditional UPDATE as the enforcement in the database, and an event per transition for side effects. Keep side effects out of the state objects: the state decides whether, listeners decide what else happens. The lab is the complete version.
Approval chain
Order the links from lowest to highest authority, give each a limit, and make "fell off the end" an explicit error. Store the chain in configuration if finance changes limits often. Log which link approved (the command log).
Undo/redo editor
Commands for each user action; History.Execute clears redo; cap the stack; for actions whose inverse is hard to compute, take a memento before executing and restore it on undo.
Audit log via command history
Every state-changing request becomes a command object; the invoker persists (user, command, payload, time) in the same transaction as the change (the command_log table above). This also gives you replay for debugging. If you need the full history as the source of truth, that is Event Sourcing, not an audit log.
Event-driven modules inside a monolith
Modules publish domain events (OrderPaid); other modules subscribe. Rules: events are past tense facts; publish after commit (ShouldDispatchAfterCommit); listeners that do I/O are queued; a listener must not assume another listener ran first. When you catch yourself writing "listener B must run after listener A", replace the pair with a Mediator.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Several interchangeable algorithms chosen by caller/config | Strategy | Go func value; Laravel container tag | Swap at runtime, test each alone |
| Fixed sequence, a few steps vary per subclass | Template Method (Go: func + interface) | final skeleton, hooks with defaults | Order cannot be broken |
| Behaviour depends on lifecycle status | State | Transition table + conditional UPDATE | Illegal transitions impossible |
| Request must pass checks that may stop it | Chain of Responsibility | Middleware, Pipeline | Reorderable, single-purpose handlers |
| Request must be queued, retried, logged or undone | Command | Jobs, idempotency key, command log | Request as data |
| Many independent reactions to one fact | Observer | Queued listeners, after-commit dispatch | Add reactions without editing the subject |
| Many objects with tangled interactions | Mediator | One coordinator per use case | n links instead of n(n−1)/2 |
| Traverse without exposing storage | Iterator | iter.Seq, LazyCollection | Flat memory, early stop |
| Restore earlier state | Memento | Versions table, bounded stack | Encapsulation preserved |
| New operations over a stable type set | Visitor | ast.Inspect; type switch if small | Operations grow, types do not |
| Business-editable conditions | Interpreter | JSON rules + validation | Change without deploy |
| Two branches that never change | No pattern | if/switch | Indirection costs more than it saves |
Strategy vs State vs Template Method
All three vary behaviour. refactoring.guru puts the first difference precisely: "Template Method is based on inheritance" while "Strategy is based on composition", and "Template Method works at the class level, so it’s static. Strategy works on the object level, letting you switch behaviors at runtime." The second: "In the State pattern, the particular states may be aware of each other and initiate transitions from one state to another, whereas strategies almost never know about each other."
| Question | Strategy | State | Template Method |
|---|---|---|---|
| Who picks the variant? | Client/config | The current state (transition) | The subclass, at compile time |
| Do variants know each other? | No | Yes (they set the next state) | No |
| Mechanism | Composition | Composition | Inheritance |
| Changes during object's life? | Rarely (set once) | Constantly | Never |
| Example | Shipping calculator | Order lifecycle | Report exporter |
Observer vs pub/sub vs Mediator
refactoring.guru describes the family: "Mediator eliminates direct connections between senders and receivers, forcing them to communicate indirectly via a mediator object" while "Observer lets receivers dynamically subscribe to and unsubscribe from receiving requests." Fowler's Event Aggregator is the in-between form: "Channel events from multiple objects into a single object to simplify registration for clients."
| Question | Observer | Pub/sub (broker) | Mediator |
|---|---|---|---|
| Who knows whom | Subject holds observer references | Nobody; both know the topic | Colleagues know the mediator; mediator knows all |
| Where rules live | In each observer | In each subscriber | In the mediator |
| Process boundary | Same process | Across processes | Usually same process (saga orchestrator across) |
| Delivery | Synchronous call | Async, durable, at-least-once | Synchronous or async |
| Laravel | Events + listeners, model observers | Queued listeners, broker packages | Coordinator Action |
| Go | Callbacks, channels | NATS, Kafka, RabbitMQ clients | Struct or goroutine owner |
Command vs Job vs Transaction Script
Fowler defines Transaction Script as one that "Organizes business logic by procedures where each procedure handles a single request from the presentation." It is about organising logic; Command is about representing the request. A Laravel Job is a Command whose invoker is a queue worker. They combine: a Job's handle() is often a transaction script.
| Command (pattern) | Laravel Job | Transaction Script | |
|---|---|---|---|
| Is the request an object? | Yes | Yes (serialised to the queue) | No, it is a procedure call |
| Can be queued/retried/undone | Yes, by design | Queued, retried ($tries, backoff) | No |
| Typical size | One action | One unit of background work | One use case |
| Example | Insert{"hi"}, RenameDocument | CapturePayment::dispatch($order) | PlaceOrderService::handle() |
In architecture: from a single process to a distributed system
Most behavioral patterns are in-process designs. As the system splits, each one either stays local or turns into a messaging pattern with a different name and stronger failure semantics.
Monolith: one process, one database
How it shows up: classes and functions. Middleware chains, events and listeners, jobs, enum state machines, strategies bound in the container.
Simplest correct usage: State on the model with a conditional UPDATE; Observer with ShouldDispatchAfterCommit; Command as queued jobs on the database or Redis queue driver; Strategy via container bindings.
Example (simple): a blog: PostStatus enum (draft, scheduled, published), a PublishScheduledPosts job run by the scheduler, a PostPublished event with a queued NotifySubscribers listener.
Example (complex): a shop: checkout Pipeline (validate, reserve stock, discount strategy, place order) inside one transaction; OrderStatus enum; OrderStatusChanged event with listeners for email, warehouse export and analytics; undoable admin edits stored in command_log.
Modular monolith and multiple databases
How it shows up: modules communicate through events (Observer) or through a coordinator (Mediator), never by calling each other's internals or writing each other's tables.
Rules: events are the published API of a module, so version them like an API; each module subscribes in its own service provider; a cross-module flow that must happen in order (reserve, invoice, notify) lives in one coordinator use case, not in a chain of listeners that call each other. If modules have separate databases, a listener in module B cannot join module A's transaction: treat it like a remote consumer and make it idempotent.
Example: Billing publishes InvoicePaid; Fulfilment listens and creates a shipment; the CheckoutMediator in the Checkout module is the only code that knows the order of Inventory → Billing → Notifications.
Microservices: patterns with a network in the middle
What survives and what changes:
| In-process pattern | Distributed form | What you must add | Read next |
|---|---|---|---|
| Observer | Publish/subscribe via a broker | Outbox, at-least-once, idempotent consumers, schema evolution | Event-Driven Architecture, Outbox |
| Command | Message on a work queue | Idempotency keys, retries with backoff, DLQ | Competing Consumers, Retry & Backoff, DLQ |
| State | Saga / durable workflow | Persisted state, timeouts, compensations | Saga, Durable Workflows |
| Mediator | Saga orchestrator / process manager | Correlation ids, state store | Advanced Routing |
| Chain of Responsibility | Gateway filters, service mesh policies, routing slip | Timeouts per hop, tracing | Advanced Routing |
| Memento | Snapshots in an event-sourced store | Snapshot + replay | Event Sourcing & CQRS |
Checkout service Broker Payment service Shipping service
1 INSERT order(pending) + outbox row in one transaction
2 relay publishes OrderPlaced -> orders topic
3 -> consume, charge, idempotency key=order id
4 <- PaymentCaptured
5 consume -> order: pending -> paid (conditional UPDATE)
6 publish OrderPaid -> -> create shipment
a lost or duplicated message must never move the state machine twiceExample: the order state machine lives in the checkout service; other services never set its status, they send events that the owner turns into transitions. That keeps one writer per state machine.
Distributed data: replicas, caches and many instances
Where in-process patterns break:
- Observer with many app instances: an in-memory subject on instance A does not notify observers on instance B. Use the queue or a broker (Redis pub/sub is fire-and-forget: subscribers that are down miss messages; Redis Streams or a real broker keep them).
- State read from a replica: a lagging read replica can show
pendingafter the primary moved topaid; transitions must read and write the primary (conditionalUPDATEdoes). - Cached state: an order status in Redis invalidated by an Eloquent observer is stale between the write and the
Cache::forget; for state machines, cache only for display. - Memento across services: a snapshot of one service's data does not include other services' data; restoring it can violate invariants that span services.
- Strategy config drift: instances must agree on which strategy is active; read the choice from shared config or a feature-flag service, not local files.
Scaling path: 1×, 10×, 100×
| Scale | Structure | Pattern practice |
|---|---|---|
| 1× (one app, one team) | Monolith | Enum state, sync listeners, jobs on database/Redis queue, Pipeline checkout |
| 10× (several teams, more traffic) | Modular monolith, queue workers scaled separately | Queued listeners, after-commit events, coordinator per use case, command log, Horizon-style worker pools |
| 100× (many services) | Services per capability, broker | Outbox + pub/sub, sagas for state machines, idempotent consumers, schema registry for event contracts |
Lab: order state machine, pipeline checkout and observers
You build the same checkout twice, in Go and in Laravel: an order state machine (State), a checkout pipeline whose steps can stop the chain and compensate (Chain of Responsibility, with a discount Strategy as one step), and listeners that react to status changes after commit (Observer).
Go setup.
cd docs/snippets/design/behavioral-patterns/go
gofmt -l . && go vet ./... # no output, no errors
go test -race ./lab/ -v # 4 tests: transitions, happy path, payment failure, empty cartThe state machine as data, events recorded on the order and pulled after "commit":
// Package lab combines three behavioral patterns into one checkout:
// a State machine for the order, a Chain of Responsibility pipeline for
// checkout steps, and Observers for side effects.
package lab
import (
"errors"
"fmt"
)
type Status string
const (
Pending Status = "pending"
Paid Status = "paid"
Shipped Status = "shipped"
Delivered Status = "delivered"
Cancelled Status = "cancelled"
Refunded Status = "refunded"
)
// transitions is the whole state machine as data: from -> allowed targets.
// The same table becomes a SQL CHECK or a lookup table in the database.
var transitions = map[Status][]Status{
Pending: {Paid, Cancelled},
Paid: {Shipped, Refunded},
Shipped: {Delivered},
}
var ErrTransition = errors.New("illegal transition")
func (s Status) CanTransitionTo(next Status) bool {
for _, t := range transitions[s] {
if t == next {
return true
}
}
return false
}
// StatusChanged is the event observers receive.
type StatusChanged struct {
OrderID string
From, To Status
}
type Order struct {
ID string
Total int64
Status Status
events []StatusChanged
}
// TransitionTo changes state and records an event; it never notifies directly,
// so the caller can publish only after the transaction commits.
func (o *Order) TransitionTo(next Status) error {
if !o.Status.CanTransitionTo(next) {
return fmt.Errorf("%w: %s -> %s", ErrTransition, o.Status, next)
}
o.events = append(o.events, StatusChanged{o.ID, o.Status, next})
o.Status = next
return nil
}
// PullEvents hands recorded events to the caller and clears them.
func (o *Order) PullEvents() []StatusChanged {
ev := o.events
o.events = nil
return ev
}The checkout chain; Reserve undoes its own work when a later step fails:
package lab
import (
"context"
"errors"
"sync"
)
// Cart is the input that flows through the checkout pipeline.
type Cart struct {
CustomerID string
Lines map[string]int // sku -> qty
Subtotal int64
Discount int64
Order *Order
}
// Next calls the rest of the pipeline.
type Next func(ctx context.Context, c *Cart) error
// Step is one handler of the chain: it may work before and after next,
// or stop the chain by returning without calling next.
type Step func(ctx context.Context, c *Cart, next Next) error
// Pipeline runs steps in order; the terminal handler places the order.
func Pipeline(steps ...Step) Next {
final := Next(func(context.Context, *Cart) error { return nil })
for i := len(steps) - 1; i >= 0; i-- {
step, next := steps[i], final
final = func(ctx context.Context, c *Cart) error { return step(ctx, c, next) }
}
return final
}
var (
ErrEmptyCart = errors.New("cart is empty")
ErrOutOfStock = errors.New("out of stock")
)
func ValidateCart(ctx context.Context, c *Cart, next Next) error {
if len(c.Lines) == 0 {
return ErrEmptyCart // stops the chain
}
return next(ctx, c)
}
// Stock is a tiny in-memory inventory; Reserve is the step's side effect.
type Stock struct {
mu sync.Mutex
Qty map[string]int
}
func (s *Stock) Reserve(ctx context.Context, c *Cart, next Next) error {
s.mu.Lock()
for sku, n := range c.Lines {
if s.Qty[sku] < n {
s.mu.Unlock()
return ErrOutOfStock
}
}
for sku, n := range c.Lines {
s.Qty[sku] -= n
}
s.mu.Unlock()
if err := next(ctx, c); err != nil {
s.mu.Lock() // compensate: the step undoes its own work on failure
for sku, n := range c.Lines {
s.Qty[sku] += n
}
s.mu.Unlock()
return err
}
return nil
}
// ApplyDiscount is a strategy plugged into a step.
func ApplyDiscount(rule func(subtotal int64) int64) Step {
return func(ctx context.Context, c *Cart, next Next) error {
c.Discount = rule(c.Subtotal)
return next(ctx, c)
}
}
// Charge is the payment port; tests pass a fake.
type Charge func(ctx context.Context, customerID string, cents int64) error
func PlaceOrder(charge Charge, newID func() string) Step {
return func(ctx context.Context, c *Cart, next Next) error {
o := &Order{ID: newID(), Total: c.Subtotal - c.Discount, Status: Pending}
if err := charge(ctx, c.CustomerID, o.Total); err != nil {
return err // Reserve, earlier in the chain, compensates
}
if err := o.TransitionTo(Paid); err != nil {
return err
}
c.Order = o
return next(ctx, c)
}
}package lab
import "sync"
// Bus is an in-process observer registry keyed by target status.
type Bus struct {
mu sync.RWMutex
listeners map[Status][]func(StatusChanged)
}
func (b *Bus) On(to Status, fn func(StatusChanged)) {
b.mu.Lock()
defer b.mu.Unlock()
if b.listeners == nil {
b.listeners = map[Status][]func(StatusChanged){}
}
b.listeners[to] = append(b.listeners[to], fn)
}
// Publish calls listeners in registration order. Call it after commit.
func (b *Bus) Publish(events ...StatusChanged) {
for _, e := range events {
b.mu.RLock()
fns := b.listeners[e.To]
b.mu.RUnlock()
for _, fn := range fns {
fn(e)
}
}
}package lab
import (
"context"
"errors"
"testing"
)
func TestTransitions(t *testing.T) {
cases := []struct {
from, to Status
ok bool
}{
{Pending, Paid, true},
{Pending, Shipped, false},
{Paid, Shipped, true},
{Shipped, Cancelled, false},
{Cancelled, Paid, false},
}
for _, c := range cases {
o := &Order{ID: "o1", Status: c.from}
err := o.TransitionTo(c.to)
if (err == nil) != c.ok {
t.Errorf("%s -> %s: err=%v, want ok=%v", c.from, c.to, err, c.ok)
}
if err != nil && !errors.Is(err, ErrTransition) {
t.Errorf("want ErrTransition, got %v", err)
}
}
}
func checkout(stock *Stock, charge Charge) Next {
return Pipeline(
ValidateCart,
stock.Reserve,
ApplyDiscount(func(s int64) int64 { return s / 10 }),
PlaceOrder(charge, func() string { return "o-1" }),
)
}
func TestCheckoutHappyPathPublishesPaid(t *testing.T) {
stock := &Stock{Qty: map[string]int{"mug": 3}}
var charged int64
charge := func(_ context.Context, _ string, cents int64) error { charged = cents; return nil }
cart := &Cart{CustomerID: "c1", Lines: map[string]int{"mug": 2}, Subtotal: 2_000}
if err := checkout(stock, charge)(context.Background(), cart); err != nil {
t.Fatal(err)
}
if charged != 1_800 || cart.Order.Status != Paid || stock.Qty["mug"] != 1 {
t.Fatalf("charged=%d status=%s stock=%d", charged, cart.Order.Status, stock.Qty["mug"])
}
var got []string
bus := &Bus{}
bus.On(Paid, func(e StatusChanged) { got = append(got, "email:"+e.OrderID) })
bus.On(Paid, func(e StatusChanged) { got = append(got, "warehouse:"+e.OrderID) })
bus.Publish(cart.Order.PullEvents()...)
if len(got) != 2 || got[0] != "email:o-1" || got[1] != "warehouse:o-1" {
t.Fatalf("observers got %v", got)
}
}
func TestPaymentFailureReleasesStock(t *testing.T) {
stock := &Stock{Qty: map[string]int{"mug": 3}}
declined := errors.New("card declined")
charge := func(context.Context, string, int64) error { return declined }
cart := &Cart{CustomerID: "c1", Lines: map[string]int{"mug": 2}, Subtotal: 2_000}
err := checkout(stock, charge)(context.Background(), cart)
if !errors.Is(err, declined) {
t.Fatalf("want declined, got %v", err)
}
if stock.Qty["mug"] != 3 {
t.Fatalf("stock not released: %d", stock.Qty["mug"])
}
}
func TestEmptyCartStopsChain(t *testing.T) {
called := false
charge := func(context.Context, string, int64) error { called = true; return nil }
err := checkout(&Stock{Qty: map[string]int{}}, charge)(context.Background(), &Cart{})
if !errors.Is(err, ErrEmptyCart) || called {
t.Fatalf("err=%v charged=%v", err, called)
}
}Laravel setup. In a Laravel 13 app with a products table (price, stock), an orders table (customer_id, total, status), the OrderStatus enum and Order model from the State snippet and the event and listeners from the Observer snippet:
<?php
// Lab: pipeline-based checkout (Chain of Responsibility) that creates an order
// whose status is an enum state machine (State) and whose changes are observed
// by listeners (Observer). Uses App\Enums\OrderStatus and App\Models\Order from State.php.
namespace App\Checkout;
use App\Enums\OrderStatus;
use App\Models\Order;
use App\Models\Product;
use App\Services\Payments;
use Closure;
use DomainException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Pipeline;
final class CheckoutData
{
public int $subtotal = 0;
public int $discount = 0;
public ?Order $order = null;
/** @param array<int, int> $lines product id => quantity */
public function __construct(public readonly int $customerId, public readonly array $lines) {}
}
final class ValidateCart
{
public function __invoke(CheckoutData $data, Closure $next): CheckoutData
{
if ($data->lines === []) {
throw new DomainException('Cart is empty'); // stops the chain
}
return $next($data);
}
}
final class ReserveStock
{
public function __invoke(CheckoutData $data, Closure $next): CheckoutData
{
foreach ($data->lines as $productId => $qty) {
// Atomic conditional decrement: no read-modify-write race.
$ok = Product::whereKey($productId)->where('stock', '>=', $qty)->decrement('stock', $qty);
if ($ok === 0) {
throw new DomainException("Product {$productId} is out of stock");
}
$data->subtotal += Product::whereKey($productId)->value('price') * $qty;
}
return $next($data); // a later failure rolls this back with the transaction
}
}
final class ApplyDiscount
{
public function __invoke(CheckoutData $data, Closure $next): CheckoutData
{
$data->discount = $data->subtotal >= 10_000 ? intdiv($data->subtotal, 10) : 0;
return $next($data);
}
}
final class PlaceOrder
{
public function __construct(private readonly Payments $payments) {} // resolved by the container
public function __invoke(CheckoutData $data, Closure $next): CheckoutData
{
$order = Order::create([
'customer_id' => $data->customerId,
'total' => $data->subtotal - $data->discount,
'status' => OrderStatus::Pending,
]);
$this->payments->charge($data->customerId, $order->total, idempotencyKey: "order-{$order->id}");
$order->transitionTo(OrderStatus::Paid); // fires OrderStatusChanged after commit
$data->order = $order;
return $next($data);
}
}
final class Checkout
{
public function __invoke(int $customerId, array $lines): Order
{
return DB::transaction(fn () => Pipeline::send(new CheckoutData($customerId, $lines))
->through([ValidateCart::class, ReserveStock::class, ApplyDiscount::class, PlaceOrder::class])
->thenReturn()
->order);
}
}<?php
namespace Tests\Feature;
use App\Checkout\Checkout;
use App\Enums\OrderStatus;
use App\Events\OrderStatusChanged;
use App\Models\Order;
use App\Models\Product;
use App\Services\Payments;
use DomainException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use RuntimeException;
use Tests\TestCase;
final class CheckoutTest extends TestCase
{
use RefreshDatabase;
public function test_state_machine_rejects_illegal_transitions(): void
{
$this->assertTrue(OrderStatus::Pending->canTransitionTo(OrderStatus::Paid));
$this->assertFalse(OrderStatus::Pending->canTransitionTo(OrderStatus::Shipped));
$this->assertFalse(OrderStatus::Cancelled->canTransitionTo(OrderStatus::Paid));
}
public function test_checkout_charges_once_and_announces_paid(): void
{
Event::fake([OrderStatusChanged::class]);
$this->mock(Payments::class)->shouldReceive('charge')->once();
$mug = Product::factory()->create(['price' => 6_000, 'stock' => 3]);
$order = (new Checkout)(customerId: 1, lines: [$mug->id => 2]);
$this->assertSame(OrderStatus::Paid, $order->status);
$this->assertSame(10_800, $order->total); // 12000 - 10% discount
$this->assertSame(1, $mug->fresh()->stock);
Event::assertDispatched(OrderStatusChanged::class,
fn (OrderStatusChanged $e) => $e->from === OrderStatus::Pending && $e->to === OrderStatus::Paid);
}
public function test_payment_failure_rolls_back_stock_and_order(): void
{
Event::fake([OrderStatusChanged::class]);
$this->mock(Payments::class)->shouldReceive('charge')->andThrow(new RuntimeException('declined'));
$mug = Product::factory()->create(['price' => 1_000, 'stock' => 3]);
$this->expectException(RuntimeException::class);
try {
(new Checkout)(customerId: 1, lines: [$mug->id => 2]);
} finally {
$this->assertSame(3, $mug->fresh()->stock);
$this->assertSame(0, Order::count());
Event::assertNotDispatched(OrderStatusChanged::class);
}
}
public function test_empty_cart_stops_the_chain(): void
{
$this->mock(Payments::class)->shouldNotReceive('charge');
$this->expectException(DomainException::class);
(new Checkout)(customerId: 1, lines: []);
}
}The Laravel version charges the card inside DB::transaction. If the commit fails after a successful charge, the money is taken and the order is gone, so the charge carries an idempotency key (order-{id}) and a reconciliation job must refund orphaned charges. Across services this becomes a saga step with a compensation.
Experiments.
- Run
go test -race ./lab/ -run TestTransitions -v. Expected:--- PASS. Add{Paid, Pending, false}to the table; it still passes. Now addPaid: {Shipped, Refunded, Pending}totransitions; the new row fails. The machine is the table. - In
TestCheckoutHappyPathPublishesPaid, swap the twobus.Oncalls. Expected: the assertion on order fails, showing that observers run in registration order. If your design needs a fixed order, use a Mediator instead. - Move
ValidateCartafterstock.Reserveincheckout(). RunTestEmptyCartStopsChain: it still passes (empty cart reserves nothing), but on a real cart you now reserve before validating. Order bugs in chains are silent; review middleware order as code. - Delete the compensation block in
Stock.Reserve. Expected:TestPaymentFailureReleasesStockfails withstock not released: 1. In Laravel the same guarantee comes fromDB::transactionaround the pipeline; across services it would need a saga compensation. - Laravel: run
php artisan test --filter=CheckoutTest. Then removeShouldDispatchAfterCommitfromOrderStatusChangedand add a failing step afterPlaceOrder; with real listeners (no fake), the paid email would be sent for an order that was rolled back. - Two terminals against PostgreSQL: run the conditional
UPDATE ... WHERE status = 'pending'forpaidin one session insideBEGIN, and the same forcancelledin another. Expected: the second waits, then reportsUPDATE 0after the first commits.
Common misconceptions
| Belief | Reality |
|---|---|
| A pattern must look like the GoF class diagram | In Go most behavioral patterns are a function type or a small interface |
| Observer is asynchronous | Classic Observer and default Laravel listeners are synchronous; queueing is a choice (ShouldQueue) |
| Observer and pub/sub are the same | Pub/sub adds a broker, decoupling in time and process, with durability and delivery semantics |
| An event bus is a Mediator | A bus routes; a Mediator owns the coordination rules |
A status column is the State pattern | The pattern is where the transition rules live; the column is just storage |
| Strategy and State are different names for one thing | Strategies are picked by clients and do not know each other; states pick the next state |
| Chain of Responsibility means only one handler acts | Middleware chains let every handler act; the GoF form stops at the first that can |
| Command means CLI command | Command is any request as an object: jobs, editor actions, queued messages |
| Undo is always Command | Memento undo stores snapshots; many editors combine both |
| Visitor makes the model extensible | It makes operations extensible and adding types harder (the expression problem) |
| Iterator is irrelevant in Go | Since Go 1.23 iter.Seq is the standard iterator; stdlib returns them |
| Template Method is fine anywhere there is a base class | It is the inheritance-based pattern; prefer composition when variants multiply |
| More patterns = better design | Every pattern adds indirection; use it when the variation is real |
| Interpreter is for building programming languages | It is for small, stable grammars; large ones need a parser or an existing engine |
Cheat sheet
| Topic | Remember |
|---|---|
| Family | Behavioral = algorithms + assignment of responsibilities + communication |
| Template Method | Fixed skeleton, variable steps; inheritance; Go: function + interface |
| Chain | Handlers in order, each may stop; middleware, Pipeline; order matters |
| State | Behaviour per state; transition table + conditional UPDATE; saga across services |
| Command | Request as object; queue, retry, undo, audit; Laravel Job, Bus::chain |
| Observer | One-to-many, in-process, sync by default; ShouldQueue, ShouldDispatchAfterCommit |
| Strategy | Interchangeable algorithm; Go func, slices.SortFunc; Laravel tags, Gates, Policies |
| Iterator | Traverse without exposing storage; iter.Seq, iter.Pull; generators, LazyCollection |
| Mediator | Hub owns interaction rules; n links not n(n−1)/2; watch for god mediator |
| Memento | Opaque snapshot; caretaker never reads it; cap history |
| Visitor | Double dispatch; new operations easy, new types hard; ast.Walk, ast.Inspect |
| Interpreter | Class per grammar rule; small DSLs; Composite tree |
| Strategy vs State | Who picks: caller vs current state |
| Observer vs pub/sub | Same process and sync vs broker, async, durable |
| Distributed forms | Observer → pub/sub + outbox; Command → job queue; State/Mediator → saga |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Your Order has if ($order->status === 'paid') in 14 places. Which pattern, and what must the database also do? Must-know
Answer
Answer: State: move allowed transitions into an enum (or state types) with canTransitionTo, and enforce them in the database with a conditional UPDATE ... WHERE status = :from so two workers cannot both transition. See State and Transition tables.
2 — What is the one-line difference between Strategy and State? Must-know
Answer
Answer: The client picks a strategy and strategies do not know each other; a state decides the next state itself. See Strategy vs State vs Template Method.
3 — A Laravel listener sends an email when an order is paid, but customers got emails for orders that were rolled back. Why, and what is the fix? Must-know
Answer
Answer: The event was dispatched inside a transaction that later rolled back, and the listener ran (or was queued) immediately. Implement ShouldDispatchAfterCommit on the event, or publish recorded events after commit. Across services use an outbox. See Synchronous vs queued notification.
4 — Why is a Laravel queued Job an instance of the Command pattern? Important
Answer
Answer: The request (constructor parameters) is an object that is serialised, queued, retried and executed later by an invoker (the worker), which calls the receiver injected into handle(). See Command.
5 — In a Go middleware chain built with Chain(h, Logging, RequireToken), which runs first, and does Logging see the 401? Important
Answer
Answer: Logging runs first (outermost) and, because it wraps the rest, it can observe the response on the way out, including the 401 written by RequireToken. See The onion.
6 — You add a new invoice line type GiftWrapLine. What happens in a Visitor design? Good to know
Answer
Answer: Every visitor interface and implementation needs a new visitGiftWrap method. Visitor makes new operations cheap and new types expensive. See Visitor.
7 — What must every Go push iterator do when yield returns false, and what must callers of iter.Pull always do? Important
Answer
Answer: Stop immediately and return (continuing to call yield panics). Callers of iter.Pull must call the returned stop function, typically with defer. See Push vs pull iterators.
8 — Your checkout listeners are "listener B must run after listener A". What is wrong and what do you use instead? Important
Answer
Answer: Observers should be independent; ordering dependencies are coordination logic. Put the ordered flow in a Mediator (a coordinator use case) and keep events for independent reactions. See Event-driven modules.
9 — Command undo or Memento undo for "apply a filter to a 4K image"? Good to know
Answer
Answer: Usually Memento (snapshot before) because the inverse of a filter is not computable; cap the history because snapshots are large. For "rename layer", Command undo is cheaper. See Undo stacks.
10 — What does Observer turn into once the subject and observers are separate services, and what three things must you add? Important
Answer
Answer: Publish/subscribe through a broker; add a transactional outbox (publish after commit reliably), idempotent consumers (at-least-once delivery), and versioned event schemas. See Microservices.
11 — Where is ast.Inspect on the Visitor spectrum? Good to know
Answer
Answer: It is Visitor without the double-dispatch boilerplate: the traversal is fixed (depth-first), the operation is a closure, and you type-switch on the node. ast.Walk is the interface form with Visit(node) Visitor. See Visitor.
Glossary
| Term | Meaning |
|---|---|
| Behavioral pattern | GoF family about algorithms, assignment of responsibilities and communication between objects |
| Gang of Four (GoF) | Gamma, Helm, Johnson, Vlissides, authors of Design Patterns (1994) |
| Template Method | Skeleton of an algorithm in a base, steps overridden by subclasses |
| Hook | A step with a default implementation that a subclass may override |
| Hollywood principle | "Don't call us, we'll call you": the framework or base class calls your code |
| Chain of Responsibility | Request passed along handlers, each may handle, pass or stop it |
| Middleware | Chain of Responsibility for HTTP requests (Laravel, net/http) |
| Pipeline | Laravel facade that sends any input through pipes with $next |
| State | Object whose behaviour changes with its internal state; states pick transitions |
| Finite state machine (FSM) | States, events and allowed transitions |
| Transition table | The state machine as data: from → allowed targets |
| Command | A request turned into an object that can be queued, logged, retried, undone |
| Invoker | Runs commands (button, worker, history) |
| Receiver | The object that does the real work for a command |
| Job | Laravel's queued Command (ShouldQueue, dispatch, Bus::chain) |
| Undo / redo stack | Two stacks of executed and undone commands; new command clears redo |
| Observer | Subject notifies subscribed observers of events, in-process |
| Subject (publisher) | The object others observe |
| Listener | Laravel's observer of an event class |
| Eloquent observer | Class with methods named after model events, registered with #[ObservedBy] |
ShouldQueue | Laravel interface that makes a listener or job run on a queue |
ShouldDispatchAfterCommit | Laravel interface that holds an event until the DB transaction commits |
| Lapsed listener | Observer never unsubscribed, kept alive by the subject (memory leak) |
| Pub/sub | Publish/subscribe through a broker; neither side knows the other |
| Event aggregator | Fowler: single object that channels events from many sources |
| Event bus | Generic in-process router of events to subscribers |
| Strategy | Family of interchangeable algorithms behind one interface |
| Tagged bindings | Laravel container tag/tagged/#[Tag] to resolve all implementations |
| Gate / Policy | Laravel authorization closures / classes; strategies for "may the user do this" |
| Iterator | Sequential access to elements without exposing representation |
iter.Seq / iter.Seq2 | Go 1.23 push iterator types yielding one or two values |
iter.Pull | Converts a push iterator into next/stop functions |
yield | Callback (Go) or keyword (PHP generators) that hands out the next element |
LazyCollection | Laravel collection backed by a generator; low memory |
| Mediator | Object that encapsulates how a set of objects interact |
| Colleague | An object that talks only to the mediator |
| Memento | Opaque snapshot of an object's state |
| Originator | The object that creates and restores mementos |
| Caretaker | Keeps mementos without reading them (stack, versions table) |
| Visitor | Operation over a fixed set of element types, one class per operation |
| Double dispatch | Choosing a method by two runtime types: element via accept, operation via visitX |
| Expression problem | Trade-off between adding types and adding operations |
ast.Walk / ast.Inspect | Go's Visitor and closure-based traversal of syntax trees |
| Interpreter | Class per grammar rule; evaluate a sentence as an expression tree |
| Terminal / nonterminal expression | Leaf rule (comparison) / composite rule (and, or) |
| Transaction Script | Fowler: business logic as one procedure per request |
| Saga | Distributed state machine of local transactions with compensations |
| Compensation | An action that semantically undoes an earlier step |
| Outbox | Table written in the same transaction as the change; relayed to the broker |
| Idempotency key | Identifier that makes a repeated command safe |
| Macroable | Laravel trait that adds methods at runtime (Collection::macro); an extension mechanism |
| Scheduler | Laravel's timetable that invokes jobs and commands (Schedule::job) |
References
- E. Gamma, R. Helm, R. Johnson, J. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994 (book not read for this page; facts via Wikipedia: Design Patterns)
- refactoring.guru: Behavioral patterns, Template Method, Chain of Responsibility, State, Command, Observer, Strategy, Iterator, Mediator, Memento, Visitor
- Wikipedia (secondary): Interpreter pattern, Mediator pattern
- Martin Fowler: Transaction Script, Event Aggregator
- Go: Range Over Function Types (Go blog), iter, sort, slices, go/ast, context, net/http
- Laravel 13: Helpers: Pipeline, Middleware, Events, Eloquent: Observers, Eloquent: Enum casting, Queues, Authorization, Collections: Lazy Collections, Macros, Service Container: Tagging, Task Scheduling
- PostgreSQL: CHECK constraints, Error codes
- MySQL 8.0: CHECK constraints, Server error reference