Skip to content

Composing Objects & the Law of Demeter ​

"'Only talk to your friends' is the motto." — Karl Lieberherr, Law of Demeter: Principle of Least Knowledge, Northeastern University

Summary: Build behaviour by assembling small objects that hold each other (composition), and let each method talk only to its immediate friends (Law of Demeter). The two ideas are one habit: hide structure, so structure can change. Focus: Composition vs inheritance, delegation and forwarding, Go embedding, PHP traits, constructor injection and the composition root, the Law of Demeter stated precisely, message chains, Tell Don't Ask, Hide Delegate vs Middle Man, immutability, pipelines and middleware, and the same law between services, in Go and Laravel. Learning goal: Read a line such as $order->customer->address->city, say which friend list it violates and what it will cost, and fix it with Hide Delegate or Tell Don't Ask without creating a pile of pointless wrapper methods.

This page is the complete reference for how objects are put together and who they may talk to. It covers the sources (Gamma et al. 1994, Lieberherr and Holland 1987-1989, Fowler's bliki), every term practitioners use (delegation, forwarding, embedding, trait, composition root, train wreck, middle man, with-er, functional option), how Go and Laravel express each idea, and what the Law of Demeter means when the "objects" are services owned by different teams. It does not re-teach coupling and cohesion, the SOLID principles or the pattern catalogue; it names them and links.

Page map ​

If you are looking forGo to
The whole chapter in a few tablesEverything in one minute
Why this chapter exists and what it tradesWhy composition and demeter
Gamma, Lieberherr, Holland, Fowler, Go, PHP traits: who said whatWhere it comes from
Has-a vs is-a, delegation, forwarding, Strategy, DecoratorComposition vs inheritance, Delegation, Patterns pointer
Go embedding, method promotion, no virtual dispatchGo embedding
PHP traits, insteadof, abstract trait methodsPHP traits
Constructor injection, DI container, composition rootObject graph assembly
The Law of Demeter: friends, one dot, exceptionsLoD precisely, One dot, Exceptions
Message chains, Tell Don't Ask, Hide Delegate, Middle ManMessage chain, Tell Don't Ask, Hide Delegate, Middle Man
With-ers, functional options, pipelines, middlewareImmutability, Pipelines
Orchestration, choreography, reaching through another serviceAcross services
Eloquent chains and Go struct reach-through, before and afterGo, Laravel
How to find violations and tell them from false alarmsMechanics
Monolith to distributed systemsIn architecture
A refactoring kata, wrong beliefs, cheat sheet, self-checkLab, Misconceptions, Cheat sheet, Self-check

Everything in one minute ​

The vocabulary. Every row is unpacked in the concepts section.

TermIn plain wordsTiny exampleWhat goes wrong without it
CompositionAn object is built from other objects it holdsCheckout holds a NotifierBehaviour is welded to a class tree
InheritanceA class takes everything from a parent classclass SmsNotifier extends NotifierFragile base class, deep trees
Delegation"I will ask my helper to do it"cart.discount.Apply(sum)Logic duplicated or inherited
ForwardingA wrapper passes the call on unchangedLogging.Send calls Next.SendCallers see the inner object
Embedding (Go)Listing a type in a struct without a field namestruct { *log.Logger }Hand-written forwarding methods
Trait (PHP)A reusable group of methods copied into a classuse HasSlug;Copy-paste across unrelated classes
Constructor injectionDependencies arrive as constructor argumentsNewCheckout(store, mailer)Hidden new, untestable code
Composition rootThe one place where the object graph is builtmain(), a service providernew scattered everywhere
Law of DemeterA method talks only to its friendsorder.ShipTo() not order.c.a.cityCallers know your internals
Message chain / train wrecka.b().c().d()$order->customer->address->cityEvery link is a break point
Tell, Don't AskTell an object what to do, do not pull its data outmonitor.setValue(3)Logic leaks into callers
Hide DelegateAdd a method that hides the walkperson.manager()Callers depend on the structure
Middle ManA class that only forwards20 one-line wrappersIndirection with no value
With-erA method that returns a changed copymoney.WithCents(5)Shared mutable state
Functional optionA function that configures a constructorNewClient(WithTimeout(d))Telescoping constructors
Pipeline / middlewareHandlers composed into a chain at runtimeChain(h, Logging, Auth)Cross-cutting code in every handler

Who a method may talk to (the friends).

FriendExampleWhy it is allowed
The object itselfthis.validate()It is the method's own object
The method's parameterspayment.Charge()The caller chose to hand them over
Objects the method createsx := NewX(); x.Run()The method owns them
The object's direct componentsthis.store.Save()The object holds them on purpose
Globals/singletons the object can seeconfig.Default()Allowed by the original law, discouraged today (hidden dependency)
Objects returned by a frienda.GetB().GetC().Do()Strangers. Not allowed

Where each idea lives in your tools.

IdeaGoLaravel (PHP 8.4)
ComposeStruct fields, small interfacesConstructor property promotion, contracts
Reuse without a treeEmbedding, interface embeddingTraits (with care), composition
Wiringmain()Service providers and the container
Runtime chainfunc(http.Handler) http.HandlerMiddleware, Pipeline
Hide structureMethods on the owning type, internal/Model methods, accessors, API Resources
ImmutabilityValue receivers, with-ers, optionsreadonly class, with* methods

Why composition and demeter ​

An object graph is a map of who knows whom. Two questions decide whether it survives change: how is a new behaviour added (by editing a class tree, or by plugging in another object?) and how far does one object see (only its neighbours, or the whole map?). Composition answers the first, the Law of Demeter answers the second. Together they keep the number of things a change can break small.

ChoiceYou gainYou pay
Composition over inheritanceSwap behaviour at runtime, test with fakes, no fragile base classMore small types, explicit wiring, forwarding code
InheritanceFree reuse, polymorphism in one stepA tight, compile-time link to the parent's internals
Obeying the Law of DemeterCallers survive structure changesExtra delegating methods (wider interfaces)
Ignoring it for plain dataShort code, no wrappersStructure leaks into every caller

Everyday picture. You pay a shop cashier. You hand over your money; you do not let the cashier reach into your wallet, count your notes and pick the ones they like. And you do not ask the cashier to open the till, take out the manager's keys and walk to the safe. Each person deals with the one next to them; what happens behind them is their business. That is "only talk to your friends", and it is also why a shop can change its till without retraining customers.

Before: $order->customer->address->cityAfter: $order->shipTo()CallerOrderCustomerAddressCallerOrderCustomerAddress3 dependencies, 3 reasons to break1 dependency; the graph is private

Three common misunderstandings, up front ​

  1. "Composition means never use inheritance." No. The advice is favour composition; inheritance is still right for a true, stable is-a relationship that respects the Liskov Substitution Principle.
  2. "The Law of Demeter means one dot per line." No. The dot count is a smell detector, not the law. strings.TrimSpace(s).ToUpper() and User::query()->where(...)->get() are fine; the law is about whose methods you call.
  3. "Go embedding is inheritance with a different syntax." No. The embedded type never calls back into the outer type. There is no virtual dispatch (Go embedding).

Where it comes from ​

YearSourceWhat it contributed
1987Ian Holland, Northeastern University (the Demeter project)The style rule that became the Law of Demeter, "Law of Good Style"
1988Lieberherr, Holland, Riel, "Object-Oriented Programming: An Objective Sense of Style", OOPSLA '88First published formal statement, the strong and weak versions
1989Lieberherr and Holland, "Assuring Good Style for Object-Oriented Programs", IEEE Software, September 1989, pp. 38-48The general formulation (cited from the author's page; the paper itself was not retrievable)
1994Gamma, Helm, Johnson, Vlissides, Design Patterns"Favor object composition over class inheritance" (p. 20, cited via Wikipedia, secondary)
2000Hunt and Thomas, The Pragmatic ProgrammerPopularised the Law for working programmers (Lieberherr's page: "A 2000 book that describes it well")
2005Fowler and Evans, "Fluent Interface"A deliberate chain of calls on one object
2013Fowler, "Tell Don't Ask"Move behaviour next to the data
2012+Go 1 (embedding, interfaces), PHP 5.4 (traits), Laravel container, pipelinesLanguage and framework forms of composition

What Lieberherr's page says. "The Law of Demeter (LoD) is a simple style rule for designing object-oriented systems. 'Only talk to your friends' is the motto. The style rule was first proposed at Northeastern University in the fall of 1987 by Ian Holland." (https://www.ccs.neu.edu/home/lieber/LoD.html).

What the 1988 paper says the rule is for. The motivation, in the authors' words: "The motivation behind this Law is to ensure that the software is as modular as possible. Any method written to obey this Law will only know about the immediate structure of the class to which it is attached." And the formal statement: "For all classes C, and for all methods M attached to C, all objects to which M sends a message must be instances of classes associated with the following classes: 1. The argument classes of M (including C). 2. The instance variable classes of C. (Objects created by M, or by functions or methods which M calls, and objects in global variables are considered as arguments of M.)" (OOPSLA '88 paper, https://www2.ccs.neu.edu/research/demeter/papers/law-of-demeter/oopsla88-law-of-demeter.pdf).

The same paper draws the line that most blog posts forget: "The Law prohibits the nesting of generic accessor function calls, which return objects that are not instance variable objects. It allows the nesting of constructor function calls. An accessor function is a function which returns an object which did exist before the function is called. A constructor function returns an object which did not exist before the function is called." That sentence is the root of the builder and value-chain exceptions.

Strong and weak. The paper also defines two readings. The strong law counts only a class's own instance variables as friends; the weak law counts inherited ones too. Its honest cost note: code under the strong law "tends to have extra methods for a given solution. This can render the code less readable in some cases." (same paper). That is the Middle Man problem, noticed in 1988.

What Fowler says about Tell Don't Ask. "Tell-Don't-Ask is a principle that helps people remember that object-orientation is about bundling data with the functions that operate on that data. It reminds us that rather than asking an object for data and acting on that data, we should instead tell an object what to do." (https://martinfowler.com/bliki/TellDontAsk.html, 5 September 2013).

What the Message Chains smell says. "A message chain occurs when a client requests another object, that object requests yet another one, and so on. These chains mean that the client is dependent on navigation along the class structure. Any changes in these relationships require modifying the client." Treatment: Hide Delegate. And the warning: "Overly aggressive delegate hiding can cause code in which it's hard to see where the functionality is actually occurring. Which is another way of saying, avoid the Middle Man smell as well." (https://refactoring.guru/smells/message-chains, a secondary summary of Fowler's catalogue; the catalogue entry itself, https://refactoring.com/catalog/hideDelegate.html, shows manager = aPerson.department.manager becoming manager = aPerson.manager).

What Effective Go says about embedding. "Go does not provide the typical, type-driven notion of subclassing, but it does have the ability to 'borrow' pieces of an implementation by embedding types within a struct or interface." And the key difference: "when we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one." (https://go.dev/doc/effective_go#embedding).

What the PHP manual says about traits. "Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies." (https://www.php.net/manual/en/language.oop5.traits.php).

What the Laravel container docs say. "Dependency injection is a fancy phrase that essentially means this: class dependencies are 'injected' into the class via the constructor or, in some cases, 'setter' methods." (https://laravel.com/docs/13.x/container).

The concepts, one by one ​

Composition vs inheritance Must-know ​

In plain words: Inheritance says "a SmsNotifier is a Notifier, and gets all its code". Composition says "a Checkout has a Notifier and asks it to send". With composition you can change the notifier without touching Checkout; with inheritance you change the class you are in.

Common misunderstanding: "Inheritance is for reuse." It is for substitutability: a subtype must be usable wherever the parent is. Reuse of code alone is better served by holding an object.

Definition: Class inheritance defines one class in terms of another at compile time (white-box reuse: the child sees the parent's internals). Object composition assembles behaviour from objects that expose only an interface (black-box reuse), and can be rearranged at runtime. The GoF sentence is "favor object composition over class inheritance" (cited via Wikipedia, which gives p. 20 of the 1994 book).

text
     Adding "log every notification" with inheritance      With composition
1    class SmsNotifier extends Notifier                    class Logging implements Notifier { Next }
2    class LoggingSmsNotifier extends SmsNotifier          new Logging(new Sms())
3    class LoggingEmailNotifier extends EmailNotifier      new Logging(new Email())
4    class LoggingRetryingSmsNotifier ...                  new Logging(new Retrying(new Sms()))
     -> classes = combinations                             -> objects = combinations, classes stay small

Real scenarios: notification channels with logging, retry and rate limiting; payment gateways with fraud checks; repositories with caching; HTTP clients with auth, retry, tracing.

QuestionInheritanceComposition
Link made whenCompile timeConstruction time or later
Visibility of the other sideParent internals (protected)Public interface only
Combining N behavioursSubclass per combinationWrap or list N objects
Test with a fakeSubclass or mock the classPass a fake of the interface
Failure modeFragile base class, Liskov violationsBoilerplate forwarding, wiring mistakes
Good fitTrue is-a, stable hierarchy, framework extension pointsAlmost everything else

Fix / how to use it. In Go there is no class inheritance at all, so "composition over inheritance" is the only mode; see Go embedding. In Laravel prefer a constructor-injected collaborator to a base class: Laravel itself offers contracts (Illuminate\Contracts\Mail\Mailer) so you can depend on an interface.

Delegation and forwarding Must-know ​

In plain words: Delegation means the object hands part of its job to a helper it holds. Forwarding means a wrapper passes the same call straight through to the inner object.

Common misunderstanding: "Delegation and forwarding are the same." They look alike. In true delegation the helper can act on behalf of the delegator (it receives the delegator's identity, self). In forwarding the helper keeps its own identity: when it calls this, it means itself. Go embedding and PHP composition are forwarding, which is why there is no virtual dispatch.

Definition: a delegating method has the shape func (c *Cart) Total() int { return c.discount.Apply(c.sum()) }. A forwarding method adds nothing: func (l Logging) Send(to, msg string) error { return l.Next.Send(to, msg) }.

text
1   caller -> Cart.Total()
2     Cart.Total() -> sum items               (Cart's own job)
3     Cart.Total() -> discount.Apply(sum)     (delegation to a component: a friend)
4   caller <- 1350

Real scenarios: a cart that delegates pricing to a discount policy; a repository that delegates caching to a cache object; a controller that delegates to an action class.

go
// Delegation, forwarding, Strategy and Decorator as composition patterns.
package main

import (
	"fmt"
	"strings"
)

// Strategy: the varying rule is a small interface held by the context.
type Discount interface {
	Apply(cents int) int
}

type NoDiscount struct{}

func (NoDiscount) Apply(c int) int { return c }

type Percent struct{ P int }

func (p Percent) Apply(c int) int { return c - c*p.P/100 }

type Cart struct {
	items    []int
	discount Discount // a direct component; Cart may talk to it
}

func NewCart(d Discount) *Cart { return &Cart{discount: d} }

func (c *Cart) Add(cents int) { c.items = append(c.items, cents) }

func (c *Cart) Total() int {
	sum := 0
	for _, i := range c.items {
		sum += i
	}
	return c.discount.Apply(sum) // delegation: Cart asks its collaborator
}

// Decorator: same interface in, same interface out, extra behaviour around.
type Notifier interface {
	Send(to, msg string) error
}

type SMS struct{ sent []string }

func (s *SMS) Send(to, msg string) error {
	s.sent = append(s.sent, to+": "+msg)
	return nil
}

type Logging struct {
	Next Notifier // forwarding target
	Log  func(string)
}

func (l Logging) Send(to, msg string) error {
	l.Log("send to " + to)
	err := l.Next.Send(to, msg)
	if err != nil {
		l.Log("failed: " + err.Error())
	}
	return err
}

type Truncate struct {
	Next Notifier
	Max  int
}

func (t Truncate) Send(to, msg string) error {
	if len(msg) > t.Max {
		msg = msg[:t.Max]
	}
	return t.Next.Send(to, msg)
}

func main() {
	c := NewCart(Percent{10})
	c.Add(1000)
	c.Add(500)
	fmt.Println(c.Total()) // 1350

	var logs []string
	sms := &SMS{}
	// Behaviour is assembled at runtime, outermost first.
	var n Notifier = Logging{Next: Truncate{Next: sms, Max: 10}, Log: func(s string) { logs = append(logs, s) }}
	_ = n.Send("+98912", "your order has shipped")
	fmt.Println(strings.Join(sms.sent, "|"), len(logs))
}

Strategy and Decorator as composition patterns Important ​

In plain words: Two Gang-of-Four patterns are composition in its plainest form. Strategy is "plug a rule into me". Decorator is "wrap me with extra behaviour and keep my interface".

Common misunderstanding: "Decorator needs an inheritance tree." In the book it used one; in Go and PHP you just implement the same interface and hold the inner object (the Logging and Truncate types in the snippet above).

Definition: Strategy: context holds an interface, the algorithm varies behind it. Decorator: a wrapper implements the interface and forwards, adding behaviour before or after. Full treatment lives in Structural patterns (Decorator, Proxy, Adapter, Facade) and Behavioral patterns (Strategy, Chain of Responsibility); this page only shows that both are composition.

PatternHoldsSame interface as the held object?Typical use
StrategyA rule objectNo (context has its own API)Pricing, sorting, retry policy
DecoratorThe object it wrapsYesLogging, caching, metrics
ProxyThe real subjectYesLazy load, access control
AdapterThe adapteeNo (converts)Wrapping a vendor SDK
Chain of ResponsibilityThe next handlerYesMiddleware, pipelines

Go embedding Must-know ​

In plain words: Writing a type name inside a struct without a field name makes that type's methods appear on the outer struct. It saves you from writing forwarding methods. It does not make the outer struct a subclass.

Common misunderstanding: "If Dog embeds Animal and overrides Speak, then Animal.Describe will call the dog's Speak." It will not. The promoted method runs with the inner Animal as its receiver, so it only ever sees Animal.Speak.

Definition: the Go specification says a field declared with a type but no explicit field name is an embedded field; its fields and methods are promoted if the selector is legal. Method-set rules: if S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T, and *S also includes those with receiver *T; if S contains *T, both include receivers T and *T (https://go.dev/ref/spec#Struct_types). Effective Go adds the name rules: "a field or method X hides any other item X in a more deeply nested part of the type", and the same name at the same depth is an error if it is used.

Inheritance (Java, PHP, C++)Embedding (Go)AnimalSpeak()Describe() { this.Speak() }Dog extends AnimalSpeak() overrideinherits Describe()AnimalSpeak()Describe() { a.Speak() }Dog struct { Animal }Speak() shadows Animal.SpeakDescribe() promoted from Animaldog.Describe() prints "Rex barks"dog.Describe() prints "Rex makes a sound"virtual dispatch: back to Dogreceiver is the inner Animalis-a
text
     d := Dog{Animal{Name: "Rex"}}                      Java / PHP: class Dog extends Animal
1    d.Speak()     -> Dog.Speak     -> "Rex barks"      same
2    d.Describe()  -> Animal.Describe (receiver: d.Animal)
3      -> a.Speak()  -> Animal.Speak -> "Rex makes a sound"   Java would call Dog.speak via virtual dispatch

Real scenarios: bufio.ReadWriter embeds *Reader and *Writer; a struct embeds *log.Logger to get Println; a wrapper embeds an io.Writer and overrides one method (counting bytes); httptest.ResponseRecorder-style wrappers. Embedding an interface and overriding a single method is Go's lightest Decorator.

FormExampleWhat it gives youWatch out
Embed a struct valuestruct { Animal }Fields and methods promotedPromoted methods become public API of the outer type
Embed a pointerstruct { *log.Logger }Same, shared instance, can be nilNil pointer panics at call time
Embed an interface in a structstruct { io.Writer }Decorator: override one method, forward the restCalling a method on a nil embedded interface panics
Embed an interface in an interfaceio.ReadWriterBigger contract from small onesOnly interfaces embed in interfaces
Embed sync.Mutexstruct { sync.Mutex }Lock/Unlock promotedExposes locking to every caller; prefer a named unexported field
Name clash at same depthAB{A; B} both with HelloAmbiguity only when usedDefine AB.Hello yourself

Fix / how to use it. Embed when you really want the promoted method set as your own API. Use a named field (and explicit forwarding) when you want to keep the collaborator private; that also keeps the Law of Demeter intact, because app.Logger.Printf would make callers depend on the embedded type.

go
// Embedding is composition with promotion. It is not inheritance:
// there is no virtual dispatch from the inner type back to the outer one.
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

// ---- 1. Method promotion and the receiver rule ----

type Animal struct{ Name string }

func (a Animal) Speak() string    { return a.Name + " makes a sound" }
func (a Animal) Describe() string { return "I am " + a.Name + "; " + a.Speak() }

type Dog struct {
	Animal // embedded: Speak and Describe are promoted to Dog
}

// Dog "overrides" Speak by shadowing it. Animal.Describe does not know.
func (d Dog) Speak() string { return d.Name + " barks" }

// ---- 2. Interface embedding builds bigger contracts from small ones ----

type ReadCloser interface {
	io.Reader
	io.Closer
}

// ---- 3. Embedding a collaborator and decorating one method ----

type countingWriter struct {
	io.Writer // the wrapped writer; every Write not redefined is forwarded
	n         int
}

func (c *countingWriter) Write(p []byte) (int, error) {
	n, err := c.Writer.Write(p)
	c.n += n
	return n, err
}

// ---- 4. Name conflicts at the same depth are ambiguous ----

type A struct{}

func (A) Hello() string { return "A" }

type B struct{}

func (B) Hello() string { return "B" }

type AB struct {
	A
	B
}

// AB.Hello() would not compile: ambiguous selector. Resolve it explicitly.
func (ab AB) Hello() string { return ab.A.Hello() + "+" + ab.B.Hello() }

func main() {
	d := Dog{Animal{Name: "Rex"}}
	fmt.Println(d.Speak())    // Rex barks
	fmt.Println(d.Describe()) // I am Rex; Rex makes a sound  <- no virtual dispatch

	var rc ReadCloser = io.NopCloser(strings.NewReader("x"))
	_ = rc.Close()

	cw := &countingWriter{Writer: os.Stdout}
	fmt.Fprintln(cw, "hello")
	fmt.Println("bytes written:", cw.n)

	fmt.Println(AB{}.Hello())
}

PHP traits Must-know ​

In plain words: A trait is a bundle of methods (and properties) that PHP copies into any class that says use TraitName;. It is copy-and-paste done by the language, not an object the class holds.

Common misunderstanding: "Traits are composition." They are horizontal reuse of code, and the result is still one class whose $this is shared with the trait. You cannot swap a trait at runtime, inject a fake of it, or hide its state: its properties become the host's properties. A collaborator object gives you those; a trait does not.

Definition: the manual says a trait cannot be instantiated on its own and reduces "some limitations of single inheritance". Precedence: "members from the current class override Trait methods, which in turn override inherited methods". Conflicts: "If two Traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved", resolved with insteadof (choose one) and as (alias or change visibility). Abstract trait methods "impose requirements upon the exhibiting class". Traits may declare static members and, since PHP 8.2, constants.

text
1   class Robot { use Talk, Greet; }            -> Fatal error: both define hello()
2   use Talk, Greet { Talk::hello insteadof Greet; Greet::hello as greetHello; }
3   (new Robot)->hello()       -> "Talk"
4   (new Robot)->greetHello()  -> "Greet"

Real scenarios: Eloquent's HasFactory, SoftDeletes, Notifiable; a HasSlug trait shared by unrelated models; a logging helper mixed into jobs.

FeatureSyntaxUse it for
Use several traitsuse A, B;Mixing unrelated capabilities
Resolve a clashA::m insteadof B;Pick the winner
Alias or visibilityB::m as protected n;Keep both or narrow access
Abstract requirementabstract public function slugSource(): string;The trait declares what the host must provide
Trait stateprivate int $n = 0;Avoid: hidden state in every host
Static membersstatic function make()Call through the class, not the trait (deprecated on the trait in 8.1)

Fix / how to use it. Use a trait for small stateless helpers and framework hooks. When the code has state, rules that change, or needs a test double, extract an interface and inject it, as in the Counter example.

php
<?php

namespace App\Support;

// 1. Conflict resolution: two traits define the same method name.
trait Talk
{
    public function hello(): string
    {
        return 'Talk';
    }
}

trait Greet
{
    public function hello(): string
    {
        return 'Greet';
    }
}

class Robot
{
    use Talk, Greet {
        Talk::hello insteadof Greet; // pick one
        Greet::hello as greetHello;  // keep the other under an alias
    }
}

// 2. An abstract trait method states what the trait needs from its host.
trait HasSlug
{
    abstract public function slugSource(): string;

    public function slug(): string
    {
        return strtolower(preg_replace('/[^A-Za-z0-9]+/', '-', $this->slugSource()));
    }
}

class Post
{
    use HasSlug;

    public function __construct(private string $title)
    {
    }

    public function slugSource(): string
    {
        return $this->title;
    }
}

// 3. Why a trait is not composition: it copies code INTO the class.
//    The host and the trait share $this, private state and one namespace.
trait Counts
{
    private int $n = 0; // becomes a property of every host class

    public function hit(): void
    {
        $this->n++;
    }
}

// Composition would be a separate object with its own state and interface:
interface Counter
{
    public function hit(): void;
}

final class InMemoryCounter implements Counter
{
    private int $n = 0;

    public function hit(): void
    {
        $this->n++;
    }
}

final class Page
{
    public function __construct(private Counter $counter) // replaceable, fakeable
    {
    }

    public function view(): void
    {
        $this->counter->hit();
    }
}

Object graph assembly: constructor injection, container, composition root Must-know ​

In plain words: Somebody has to create the objects and connect them. Put all of that in one place near the entry point, and let every other class receive what it needs.

Common misunderstanding: "A DI container is dependency injection." Injection is just passing dependencies in. A container is a tool that automates the passing. Calling the container from inside business code (app()->make(...), resolve(...)) is the Service Locator anti-pattern: the dependency is hidden again.

Definition: Constructor injection: required collaborators are constructor parameters. Composition root: the single place (main in Go, service providers and bootstrap/app.php in Laravel) that knows concrete types and builds the graph. Laravel's container does "zero configuration resolution": it autowires a constructor whose parameters are concrete classes; for interfaces you bind ($this->app->bind(Interface::class, Concrete::class)).

Composition root: main() or a service providerthe only code that says "new"; builds leaves first, passes them inCheckoutconstructor(OrderStore, Notifier)interface OrderStoreinterface NotifierPgStoreimplements OrderStoreSmtpNotifierimplements Notifiernew Checkout(store, mail)usesusesimplemented byimplemented by
text
1   main()                     -> store  := &memStore{}
2   main()                     -> mailer := logMailer{}
3   main()                     -> co     := app.NewCheckout(store, mailer, systemClock{})
4   co.Place(ctx, order)       -> store.Save -> mailer.Send     (app package never says "new")

Real scenarios: swapping the real mailer for a log mailer in staging; a clock interface so tests do not sleep; a repository interface so unit tests need no database.

TechniqueGoLaravelComment
Constructor injectionNewCheckout(s, m, c)__construct(private OrderStore $store)Default choice
Setter / method injectionRare, optional dependency$container->call(), controller method type-hintsFor optional or per-call values
Containergoogle/wire (compile-time codegen), uber-go/fx (runtime); many Go teams hand-wire in mainBuilt in: bind, singleton, contextual binding, taggingName the product; do not assume one
Service locatorGlobal registry lookupapp(Foo::class) in domain codeAvoid in business classes
Poor man's DIWire by hand in mainWire by hand in a providerFine up to dozens of types

Fix / how to use it. Go: interfaces are declared where they are consumed, one or two methods each; main builds leaves first. Laravel: bind contracts in a service provider; type-hint contracts in constructors; use contextual binding when two classes need different implementations.

go
// Command shop is the composition root: the only place that knows which
// concrete type implements which interface. Everything is built here, once.
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"academy/composition-law-of-demeter/root/app"
)

type memStore struct{ rows map[string]app.Order }

func (m *memStore) Save(_ context.Context, o app.Order) error {
	m.rows[o.ID] = o
	return nil
}

type logMailer struct{ l *log.Logger }

func (m logMailer) Send(_ context.Context, to, subject string) error {
	m.l.Printf("mail to=%s subject=%q", to, subject)
	return nil
}

type systemClock struct{}

func (systemClock) Now() string { return time.Now().UTC().Format(time.RFC3339) }

func main() {
	// 1. leaves first
	store := &memStore{rows: map[string]app.Order{}}
	mailer := logMailer{l: log.Default()}
	// 2. then the objects that use them
	checkout := app.NewCheckout(store, mailer, systemClock{})
	// 3. then run
	err := checkout.Place(context.Background(), app.Order{ID: "42", Cents: 1999, Email: "sara@example.com"})
	fmt.Println("placed:", err == nil, len(store.rows))
}
php
<?php

namespace App\Checkout;

use Illuminate\Contracts\Mail\Mailer as MailerContract;
use Illuminate\Support\ServiceProvider;

interface OrderStore
{
    public function save(array $order): void;
}

interface Notifier
{
    public function send(string $to, string $message): void;
}

final class EloquentOrderStore implements OrderStore
{
    public function save(array $order): void
    {
        \App\Models\Order::query()->create($order);
    }
}

// Constructor injection: dependencies are required and visible.
final class Checkout
{
    public function __construct(
        private readonly OrderStore $store,
        private readonly Notifier $notifier,
    ) {
    }

    public function place(array $order): void
    {
        $this->store->save($order);
        $this->notifier->send($order['email'], 'Order received');
    }
}

// Decorator: same contract, extra behaviour, wrapped around another Notifier.
final class LoggingNotifier implements Notifier
{
    public function __construct(
        private readonly Notifier $inner,
        private readonly \Psr\Log\LoggerInterface $log,
    ) {
    }

    public function send(string $to, string $message): void
    {
        $this->log->info('notify', ['to' => $to]);
        $this->inner->send($to, $message); // forwarding
    }
}

final class MailNotifier implements Notifier
{
    public function __construct(private readonly MailerContract $mailer)
    {
    }

    public function send(string $to, string $message): void
    {
        $this->mailer->raw($message, fn ($m) => $m->to($to)->subject('Shop'));
    }
}

// The service provider is the composition root: the one place that knows
// which concrete class stands behind which contract.
final class CheckoutServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(OrderStore::class, EloquentOrderStore::class);

        $this->app->bind(Notifier::class, fn ($app) => new LoggingNotifier(
            $app->make(MailNotifier::class),
            $app->make(\Psr\Log\LoggerInterface::class),
        ));
        // Checkout itself needs no binding: the container autowires its constructor.
    }
}

The Law of Demeter, stated precisely Must-know ​

In plain words: A method may send messages only to a short list of "friends". Anyone else it learns about by asking a friend is a stranger.

Common misunderstanding: "The law is about not using too many dots." It is about types you depend on. A method that calls a.b().c() depends on the types of a, b() and c(); if b changes shape, this method breaks even though it never mentions B by name.

Definition (for functions). A method m of object a may call methods only on: (1) a itself; (2) m's parameters; (3) objects created inside m; (4) a's direct components (fields); (5) globals visible to a (listed in the original; modern style treats them as hidden dependencies and avoids them). This list is the one on Wikipedia, whose wording follows the 1988 paper (arguments, instance variables, created objects and globals counted as arguments).

method m of a(class C)1. a itselfthis.other()2. parameters of mp.doIt()3. created inside mx = new X(); x.run()4. direct componentsthis.field.call()a component, bfriend: b.getC() is allowedthe object c it returnedstranger: c.doIt() is notreturned by
text
1   func (a *A) m(p P) {
2     a.helper()            // ok: self
3     p.Run()               // ok: parameter
4     x := NewX(); x.Do()   // ok: created here
5     a.b.Call()            // ok: direct component
6     a.b.Get().Call()      // NOT ok: Get() returned an object a does not own
7   }

Real scenarios: reading a customer's city from an order; finding a manager through a department; a controller that digs through a request's nested arrays; a service that parses another service's JSON three levels deep.

VersionFriendsConsequence
Strong law (1988)Parameters, own (non-inherited) instance variablesMaximum structure hiding, most delegating methods
Weak law (1988)Also inherited instance variablesSlightly wider reach, weaker change isolation
Wikipedia / Hunt-Thomas "for functions"self, parameters, created, components, globalsThe rule most teams quote
"Only talk to your friends who share your concerns" (Lieberherr, 2004, LoDC)Friends plus a concern filterPointer to aspect-oriented ideas; not needed day to day

Fix / how to use it. Replace the stranger-walk with a method on the nearest friend (Hide Delegate), or move the behaviour to where the data lives (Tell Don't Ask), or pass the thing you need as a parameter.

The "one dot" heuristic and its misreadings Important ​

In plain words: "Use one dot" is a quick way to spot a possible violation. It is a smell, not a verdict.

Common misunderstanding: "Any line with two dots breaks the law, and a line with one dot never does." Neither is true. name.trim().toUpperCase() has two dots and talks to strings (values that return new values). order.customer.address has two dots and is a real violation. And a.getB() with one dot already hands out a stranger that the next line may call.

Definition: the heuristic works when each dot is a call that returns an existing object owned by someone else. It misfires on chains that return a new object (builders, value types, streams).

ExpressionDotsViolation?Why
$order->shipTo()1NoDirect friend
$order->customer->address->city3YesTwo hops through objects the order owns
str.trim().toUpperCase()2NoEach call returns a new value
User::query()->where()->orderBy()->get()3NoFluent builder: one object, same type
$items->map(...)->filter(...)->sum()3NoCollection pipeline over values
cfg.Server.TLS.Cert (plain struct fields)3Gray areaData structure, not behaviour (see exceptions)
$a = $order->customer; $a->address->city2 across linesYesA temporary variable does not remove the stranger

Fix / how to use it. Do not count dots in code review; ask "whose structure am I depending on?". Tools only flag candidates (see Mechanics).

Exceptions: fluent builders, DTOs and value chains Important ​

In plain words: Some chains are fine because they do not walk through other objects' internals.

Common misunderstanding: "If I follow the law strictly I must wrap every field of every data class." That is the Middle Man trap. The law protects behaviour-bearing objects whose structure can change; it does not forbid reading a plain data record.

Definition: three families are accepted in practice. (1) Fluent interfaces and builders: Fowler and Evans coined "fluent interface" for APIs "designed to be readable and to flow"; every call returns the same builder (or a new one of the same kind), so you are talking to one friend repeatedly. The 1988 paper itself allows "the nesting of constructor function calls" (calls that return new objects). (2) Value chains: immutable values returning new values (money.Add(x).Round(), strings, dates, collections). (3) DTOs and plain data structures: records with public fields and no behaviour (decoded JSON, config structs, API Resources). Their structure is their interface.

text
1   $q = User::query();              // one builder
2   $q = $q->where('active', true);  // returns the builder (same friend)
3   $q = $q->orderBy('name');        // same friend
4   $users = $q->limit(10)->get();   // result is a Collection of models (new objects)
5   $users->first()->profile->bio    // <- NOT a builder chain: this is a graph walk
Chain typeExampleSafe becauseDanger sign
Fluent builderPipeline::send($x)->through([...])->thenReturn()Always the same objectBuilder mutates shared global state
Query builderDB::table('orders')->where(...)->get()A DSL, one objectReturns models, then you walk them
Value chainmoney.Add(a).Round()New values, no shared structureHidden I/O inside a getter
DTO / configcfg.Server.TimeoutData without behaviourPass cfg.Server instead of cfg to narrow knowledge
Domain object graphorder.customer.address.cityNeverAlways a violation

Fix / how to use it. When a DTO is deep, give the consumer the slice it needs (NewClient(cfg.Server)) so that the consumer does not know the whole shape.

Message chain and train wreck Must-know ​

In plain words: A line like a.b().c().d() that makes the caller learn the whole path to its answer. Each . is a place that can break, return null or trigger a query.

Common misunderstanding: "It is harmless; it is just one expression." Cost is not in the line. It is in every other line that does the same walk: when the structure changes, you edit them all, and tests must build the whole graph.

Definition: the Message Chains smell (Fowler, in the Couplers group): "a client requests another object, that object requests yet another one, and so on", so the client "is dependent on navigation along the class structure". "Train wreck" is the popular nickname for the same shape; it is a metaphor, not a term from the primary sources read for this page.

text
1   ShippingLabelController.show($order)
2     -> $order->customer           (query 1 if lazy loaded; null if no customer)
3       -> ->address                 (query 2; null if no address)
4         -> ->city                  (finally, a string)
5   customers.address_id renamed to address_ref   => every caller edited and re-tested
sql
-- What the chain does in a list of 50 orders, with lazy loading (the Eloquent default):
select * from orders limit 50;                       -- 1
select * from customers where id = ? limit 1;        -- x 50
select * from addresses where customer_id = ? limit 1;  -- x 50
-- 101 queries. With eager loading it is 3: orders, customers where id in (...), addresses where customer_id in (...).

Real scenarios: a Blade view that prints the customer's city through three arrows, repeated in six templates; an API serializer with deep nesting; a Go handler with req.Body.User.Profile.Address.City.

SmellSymptomTreatmentProduct note
Message chaina.b().c().d()Hide Delegate or Move MethodFowler catalogue
Feature envyMethod uses another object's data more than its ownMove MethodSee smells chapter
N+1 queries from a chainChain in a loop with lazy loadingEager load and hide the walkEloquent with(), Model::preventLazyLoading()
Null cascade?-> everywhereNull Object, validate at the boundaryPHP ?->, Go nil checks

Fix / how to use it. See the full before/after in Go and Laravel.

Tell, Don't Ask Must-know ​

In plain words: Do not take an object's data, decide something and push the result back. Tell the object what you want and let it decide.

Common misunderstanding: "Tell Don't Ask means no getters." Getters are fine for values you display or serialise. The principle targets decisions: if (order.getStatus() == PAID) order.setStatus(SHIPPED) belongs inside order.ship().

Definition: Fowler: "rather than asking an object for data and acting on that data, we should instead tell an object what to do. This encourages to move behavior into an object to go with the data." His example moves the value > limit check from the caller into TellMonitor.setValue. It also lowers the number of friends a caller needs.

text
     Ask                                              Tell
1    if am.getValue() > am.getLimit()                 tm.setValue(3)
2        am.getAlarm().warn(am.getName() + "...")       -> inside: if value > limit: alarm.warn(...)
     caller knows 4 getters + alarm type              caller knows 1 method

Real scenarios: invoice.markPaid() instead of setting three fields; cart.addItem(item) that enforces limits instead of callers checking; account.withdraw(100) that rejects overdraft.

StyleCaller doesObject doesRisk
AskReads, decides, writesStores dataRules duplicated in every caller; invariants broken
TellSends one commandDecides, enforces invariantsGod object if everything moves in; keep SRP
Query for displayReads valuesExposes valuesFine: this is not a decision
Command + query split (CQS)Commands change, queries returnBoth kinds existKeeps tell and ask honest

Fix / how to use it. Move the if into the class that owns the data; keep the class small with SRP.

Hide Delegate Important ​

In plain words: If clients keep walking through your helper to reach something, add a method on you that does the walk.

Common misunderstanding: "Hide Delegate means copying every method of the delegate onto me." Hide only what clients really use, and name it in your language (shipTo(), not getCustomerAddress()).

Definition: refactoring from manager = aPerson.department.manager to manager = aPerson.manager, with Person gaining get manager() { return this.department.manager } (refactoring.com catalog). It is the inverse of Remove Middle Man.

text
1   before:  Controller -> Order -> Customer -> Address   (controller imports 3 models)
2   refactor: add Order.shipTo()  (body: this.customer.address -> Destination)
3   after:   Controller -> Order.shipTo()                  (controller imports 1 model + 1 value)
4   later:   Address gains 'region'  -> only Order.shipTo() changes
MoveWhenResult
Hide DelegateMany callers walk the same pathOne place knows the path
Extract value (Destination)Callers need a few fieldsCallers depend on a small stable type
Move MethodThe caller does the work with the dataBehaviour sits with the data
Pass a parameterOnly one caller needs itNo new method on the owner

Fix / how to use it. Hide the delegate behind a domain-named method; do not generate one wrapper per field.

Middle Man Important ​

In plain words: If most of a class's methods only forward to another class, the class is dead weight.

Common misunderstanding: "Strict Law of Demeter means wrapping everything, so a lot of forwarding is correct." The paper itself warned the strong law "tends to have extra methods". Wikipedia puts it plainly: if a wrapper is needed for many calls, the called object "should have been a dependency in the calling class".

Definition: the Middle Man smell: "If most of a method's classes delegate to another class, Remove Middle Man is in order" (refactoring.guru). Exceptions: "A middle man may have been added to avoid interclass dependencies. Some design patterns create middle man on purpose (such as Proxy or Decorator)."

text
1   class Order { getCity(){return customer.getAddress().getCity();}   getZone(){...}  getStreet(){...}  getName(){...}  ... 14 more }
2   callers now use order.getX() for everything -> Order is a facade for Customer
3   fix: give callers the Customer (or a Destination value) they actually need; remove the 14 wrappers
SituationHide DelegateRemove Middle Man
1-3 domain-named methods used by many callersYesNo
15 pass-through gettersNoYes
Wrapper adds caching, logging, authKeep (it is a Decorator/Proxy)No
Wrapper isolates a vendor SDKKeep (it is an Adapter)No

Fix / how to use it. Review the owner class: if more than half of its public methods are one-line forwards to the same field, expose that field's interface instead, or inject the collaborator where it is needed.

Immutability and composition Important ​

In plain words: Objects that never change after construction can be shared freely. To "change" one, you build a modified copy.

Common misunderstanding: "Immutable means slow." Copying a small value is cheap and removes whole classes of bugs; for large structures, persistent or structural-sharing designs exist. And "immutable" is about the object's state, not about the program having no state.

Definition: a with-er is a method returning a modified copy (money.WithCents(5)). In Go, value receivers copy the struct, so func (m Money) WithCents(c int64) Money { m.cents = c; return m } is safe. Functional options configure a constructor with variadic functions: Rob Pike's 2014 post "Self-referential functions and the design of options" describes the idea, and it is the standard way Go libraries grow options without breaking callers. In PHP 8.4 use readonly class and new static(...) in with-ers.

text
1   a := NewMoney(1000, "USD")
2   b := a.Add(NewMoney(250, "USD"))   // copy; a unchanged
3   a -> 10.00 USD ; b -> 12.50 USD    // safe to hand a to any other object
TechniqueGoPHP 8.4 / LaravelGain
With-erValue receiver returning the copywithCents(): static on a readonly classSafe sharing
Functional optionNewClient(url, WithTimeout(d))Named arguments, config objectsBackwards-compatible constructors
Builderstrings.Builder, custom buildersMailable, query builderStep-by-step construction
Value objectSmall struct, no pointerreadonly class, Eloquent castsEquality by value
Immutable datetime.Time is a valueCarbonImmutable (Date::use(CarbonImmutable::class))No accidental mutation

Fix / how to use it. Make configuration and domain values immutable; keep mutation inside a few entity types.

go
// Immutability and composition: with-ers on a value type, functional
// options on a constructor.
package main

import (
	"fmt"
	"time"
)

// ---- with-ers: every "change" returns a new value ----

type Money struct {
	cents    int64
	currency string
}

func NewMoney(cents int64, cur string) Money { return Money{cents, cur} }

func (m Money) WithCents(c int64) Money { m.cents = c; return m } // m is a copy
func (m Money) Add(o Money) Money       { m.cents += o.cents; return m }
func (m Money) String() string {
	return fmt.Sprintf("%d.%02d %s", m.cents/100, m.cents%100, m.currency)
}

// ---- functional options (Rob Pike, 2014; Dave Cheney, 2014) ----

type Client struct {
	baseURL string
	timeout time.Duration
	retries int
}

type Option func(*Client)

func WithTimeout(d time.Duration) Option { return func(c *Client) { c.timeout = d } }
func WithRetries(n int) Option           { return func(c *Client) { c.retries = n } }

func NewClient(baseURL string, opts ...Option) *Client {
	c := &Client{baseURL: baseURL, timeout: 5 * time.Second, retries: 2} // safe defaults
	for _, o := range opts {
		o(c)
	}
	return c
}

func main() {
	a := NewMoney(1000, "USD")
	b := a.Add(NewMoney(250, "USD"))
	fmt.Println(a, b) // 10.00 USD 12.50 USD: a is unchanged

	c := NewClient("https://api.example.com", WithTimeout(time.Second), WithRetries(5))
	fmt.Println(c.baseURL, c.timeout, c.retries)
}
php
<?php

namespace App\Support;

use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;

// Immutability: a readonly value object with "with-ers" that return a copy.
final readonly class Money
{
    public function __construct(public int $cents, public string $currency)
    {
    }

    public function withCents(int $cents): static
    {
        return new static($cents, $this->currency);
    }

    public function add(self $other): static
    {
        return $this->withCents($this->cents + $other->cents);
    }
}

// Runtime composition with macros: add behaviour to a framework class from the outside.
final class MacroServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Collection::macro('toCents', function () {
            /** @var Collection $this */
            return $this->map(fn ($v) => (int) round($v * 100));
        });
    }
}

// Fluent interface exception: a builder returns $this by design, so the chain
// talks to ONE object (the query builder) many times, not to many strangers.
//   User::query()->where('active', true)->orderBy('name')->limit(10)->get();

Composing behaviour at runtime: pipelines and middleware Must-know ​

In plain words: Build a list of small steps, each passing the request to the next. You change behaviour by changing the list, not the steps.

Common misunderstanding: "Middleware is a framework feature." It is the Decorator/Chain of Responsibility pattern as a function: func(Handler) Handler.

Definition: in Go's net/http, Handler is an interface with ServeHTTP(ResponseWriter, *Request), and HandlerFunc adapts a function to it. A middleware takes a handler and returns a handler. In Laravel, the Pipeline facade sends an input "through a series of invokable classes, closures, or callables", each receiving the input and a $next closure; the docs say it is "very similar to middleware". Class names are built by the container, so stages can take injected dependencies.

text
1   request -> Logging.start
2     -> RequireKey            (header missing: write 403, return; next never called)
3       -> handler            (hello)
4     <- RequireKey
5   <- Logging.finish (log method, path, duration)
ConcernGoLaravelShort-circuit?
Logging, tracingLogging(l) middlewareGlobal/route middlewareNo
AuthenticationRequireKey middlewareauth middleware, EnsureTenantIsActiveYes (401/403)
Rate limitMiddleware with token bucketthrottle middlewareYes (429)
Multi-step workflowSlice of funcsPipeline::send()->through([...])Per stage
Cross-cutting around a serviceDecorator typeDecorator bound in providerOptional

Fix / how to use it. Keep stages stateless or inject state; order matters (outermost runs first), so document it.

go
// A net/http middleware chain: behaviour composed at runtime from small
// func(http.Handler) http.Handler values.
package main

import (
	"log"
	"net/http"
	"net/http/httptest"
	"time"
)

type Middleware func(http.Handler) http.Handler

// Chain wraps h so that the first middleware in the list runs outermost.
func Chain(h http.Handler, ms ...Middleware) http.Handler {
	for i := len(ms) - 1; i >= 0; i-- {
		h = ms[i](h)
	}
	return h
}

func Logging(l *log.Logger) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			next.ServeHTTP(w, r)
			l.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
		})
	}
}

func RequireKey(key string) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Header.Get("X-Api-Key") != key {
				http.Error(w, "forbidden", http.StatusForbidden) // short-circuit
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

func hello(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("hello")) }

func main() {
	h := Chain(http.HandlerFunc(hello), Logging(log.Default()), RequireKey("s3cret"))
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
	log.Println("status without key:", rec.Code)
}
php
<?php

namespace App\Orders;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Pipeline;
use Symfony\Component\HttpFoundation\Response;

// 1. Pipeline: behaviour composed at runtime from small invokable stages.
final class ApplyCoupon
{
    public function __invoke(array $cart, Closure $next): mixed
    {
        if (($cart['coupon'] ?? null) === 'WELCOME10') {
            $cart['total'] = (int) round($cart['total'] * 0.9);
        }

        return $next($cart);
    }
}

final class AddShipping
{
    public function __invoke(array $cart, Closure $next): mixed
    {
        $cart['total'] += 1200;

        return $next($cart);
    }
}

final class PriceCart
{
    public function price(array $cart): array
    {
        // Class names are resolved through the service container,
        // so each stage can take its own constructor dependencies.
        return Pipeline::send($cart)
            ->through([ApplyCoupon::class, AddShipping::class])
            ->thenReturn();
    }
}

// 2. Middleware has the same shape, with a Request in and a Response out.
final class EnsureTenantIsActive
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->user()?->tenant?->isActive()) {
            abort(403); // short-circuit: $next is never called
        }

        return $next($request);
    }
}

// bootstrap/app.php registers it:
//   ->withMiddleware(fn (Middleware $m) => $m->append(EnsureTenantIsActive::class))

Composition across services Important ​

In plain words: The Law of Demeter applies between services too. A service should not call three other services to assemble a fact, or read another service's tables.

Common misunderstanding: "Microservices are loosely coupled by definition." A service that navigates orders to customers to addresses over HTTP is a distributed train wreck: same coupling, plus latency and partial failure.

Definition: Orchestration has one coordinator that tells others what to do (Tell Don't Ask at system scale). Choreography has services react to published events. The LoD analogue is: consume what a service publishes for you (an event or an API designed for your use), never what it merely stores. Event-carried state transfer puts the needed snapshot in the event so the consumer keeps a local copy (event-driven architecture). API composition and the BFF assemble views for a client in one place instead of in every client.

text
     Before (reach-through)                          After (publish what is needed)
1    shipping -> orders.GetOrder(id)                 orders -> publishes OrderPlaced{orderId, shipTo{city,zone}}
2    shipping -> customers.GetCustomer(cid)          shipping <- consumes, stores its own row
3    shipping -> addresses.GetAddress(aid)           shipping.CityFor(orderId) = local read
4    3 network hops, 3 failure modes                 0 network hops at read time; at-least-once => idempotent upsert
ApproachCouplingFailure modeUse when
Chain of synchronous callsHigh: knows 3 servicesAny one down breaks itAlmost never
Shared database / read other's tablesHighestSchema change breaks allOnly inside a modular monolith boundary with owned views
Orchestration (one coordinator)Medium: coordinator knows stepsCoordinator availabilityClear workflow, saga orchestration
Choreography (events)Low: knows eventsHard to trace flowIndependent reactions
Event-carried state transferLow: knows one eventStale data until consumedRead-heavy consumers
API composition / BFFMedium, one placeAggregator is a dependencyScreens that need many services

Fix / how to use it. Publish an event with the snapshot consumers need; consume it idempotently (inbox); never share tables (data ownership).

go
// Package before is a network train wreck: the shipping service walks
// orders -> customers -> addresses with three synchronous calls.
package before

import (
	"context"
	"fmt"
)

type Orders interface {
	GetOrder(ctx context.Context, id string) (customerID string, err error)
}

type Customers interface {
	GetCustomer(ctx context.Context, id string) (addressID string, err error)
}

type Addresses interface {
	GetAddress(ctx context.Context, id string) (city string, err error)
}

type Shipping struct {
	orders    Orders
	customers Customers
	addresses Addresses
}

func New(o Orders, c Customers, a Addresses) *Shipping { return &Shipping{o, c, a} }

// CityFor makes three remote calls. It fails if any of three services is
// down, and breaks when any of three teams renames a field.
func (s *Shipping) CityFor(ctx context.Context, orderID string) (string, error) {
	cid, err := s.orders.GetOrder(ctx, orderID)
	if err != nil {
		return "", fmt.Errorf("orders: %w", err)
	}
	aid, err := s.customers.GetCustomer(ctx, cid)
	if err != nil {
		return "", fmt.Errorf("customers: %w", err)
	}
	return s.addresses.GetAddress(ctx, aid)
}
go
// Package after uses event-carried state transfer: orders publishes what
// shipping needs, and shipping keeps its own small copy.
package after

import (
	"context"
	"sync"
)

// OrderPlaced is a published contract. It carries the shipping snapshot, so
// consumers do not have to navigate through other services.
type OrderPlaced struct {
	OrderID string
	ShipTo  struct {
		City string
		Zone string
	}
}

type Shipping struct {
	mu     sync.RWMutex
	cities map[string]string // shipping's own read model, keyed by order id
}

func New() *Shipping { return &Shipping{cities: map[string]string{}} }

// Handle is the subscriber side. Make it idempotent: delivery is at-least-once.
func (s *Shipping) Handle(_ context.Context, e OrderPlaced) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.cities[e.OrderID] = e.ShipTo.City
	return nil
}

// CityFor is a local read: no network, no other service's availability.
func (s *Shipping) CityFor(orderID string) (string, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	c, ok := s.cities[orderID]
	return c, ok
}
php
<?php

namespace App\Shipping;

use Illuminate\Support\Facades\Http;

// Before: a network train wreck. Three services, three calls, three failure modes.
final class CityLookup
{
    public function cityFor(string $orderId): string
    {
        $order    = Http::get("http://orders/api/orders/{$orderId}")->throw()->json();
        $customer = Http::get("http://customers/api/customers/{$order['customer_id']}")->throw()->json();
        $address  = Http::get("http://addresses/api/addresses/{$customer['address_id']}")->throw()->json();

        return $address['city'];
    }
}

// After: event-carried state transfer. Orders publishes what shipping needs.
namespace App\Orders\Events;

final readonly class OrderPlaced
{
    public function __construct(
        public string $orderId,
        public string $shipToCity,
        public bool $shipToRemote,
    ) {
    }
}

namespace App\Shipping\Listeners;

use App\Orders\Events\OrderPlaced;
use App\Shipping\ShipmentDestination;

final class RememberDestination
{
    public function handle(OrderPlaced $event): void
    {
        // Idempotent upsert into shipping's OWN table; delivery is at-least-once.
        ShipmentDestination::updateOrCreate(
            ['order_id' => $event->orderId],
            ['city' => $event->shipToCity, 'remote' => $event->shipToRemote],
        );
    }
}

Why tests get easier Must-know ​

In plain words: If an object receives its collaborators and talks to few of them, a test needs few fakes.

Common misunderstanding: "Tests need a mocking framework." In Go, a three-line struct implementing a one-method interface is the fake. In PHP an anonymous class does it.

Definition: the number of objects a test must construct equals the number of friends the code under test touches (plus what they need). A chain pulls in the whole graph; composition plus the Law of Demeter pulls in exactly the interfaces the code declares.

text
     Test of ShippingFee                         before                      after
1    objects built                               Order+Customer+Address      Destination (one struct)
2    fields set to make the rule reachable       6                           2
3    test breaks when Address gains a field      yes (constructor change)    no
Test aidGoPHP / Laravel
Fake of a one-method interfaceA struct with the methodAnonymous class implementing the contract
Fake clockClock interfaceCarbon::setTestNow() or a clock interface
Fake HTTPhttptest.NewServerHttp::fake()
Fake mailA Mailer fakeMail::fake()
Container swapPass a different value in main/test$this->app->bind(Notifier::class, FakeNotifier::class) in the test

Fix / how to use it. Write the test first for a collaborator-heavy class: if the setup is long, the design has too many friends.

go
package app

import (
	"context"
	"errors"
	"testing"
)

type fakeStore struct {
	saved []Order
	err   error
}

func (f *fakeStore) Save(_ context.Context, o Order) error {
	if f.err != nil {
		return f.err
	}
	f.saved = append(f.saved, o)
	return nil
}

type fakeMailer struct{ subjects []string }

func (f *fakeMailer) Send(_ context.Context, _, subject string) error {
	f.subjects = append(f.subjects, subject)
	return nil
}

type fixedClock struct{}

func (fixedClock) Now() string { return "T0" }

// No database, no SMTP, no real clock: three tiny fakes are the whole setup.
func TestPlaceSavesAndNotifies(t *testing.T) {
	st, ml := &fakeStore{}, &fakeMailer{}
	co := NewCheckout(st, ml, fixedClock{})
	if err := co.Place(context.Background(), Order{ID: "7", Cents: 100, Email: "a@b.c"}); err != nil {
		t.Fatal(err)
	}
	if len(st.saved) != 1 || st.saved[0].Status != "placed at T0" || len(ml.subjects) != 1 {
		t.Fatalf("unexpected state: %+v %+v", st.saved, ml.subjects)
	}
}

func TestPlaceDoesNotMailWhenSaveFails(t *testing.T) {
	boom := errors.New("db down")
	st, ml := &fakeStore{err: boom}, &fakeMailer{}
	err := NewCheckout(st, ml, fixedClock{}).Place(context.Background(), Order{ID: "7", Cents: 100})
	if !errors.Is(err, boom) || len(ml.subjects) != 0 {
		t.Fatalf("err=%v mails=%v", err, ml.subjects)
	}
}
php
<?php

namespace Tests\Unit;

use App\Checkout\Checkout;
use App\Checkout\Notifier;
use App\Checkout\OrderStore;
use PHPUnit\Framework\TestCase;

// Plain PHPUnit: no database, no mail, no container, no framework boot.
final class CompositionTest extends TestCase
{
    public function test_place_saves_then_notifies(): void
    {
        $store = new class implements OrderStore {
            public array $saved = [];

            public function save(array $order): void
            {
                $this->saved[] = $order;
            }
        };
        $notifier = new class implements Notifier {
            public array $sent = [];

            public function send(string $to, string $message): void
            {
                $this->sent[] = [$to, $message];
            }
        };

        (new Checkout($store, $notifier))->place(['id' => 1, 'email' => 'a@b.c']);

        $this->assertCount(1, $store->saved);
        $this->assertSame([['a@b.c', 'Order received']], $notifier->sent);
    }
}

Per-language and per-framework view ​

PlatformReuse mechanismHides structure byWiringNotes
GoStruct fields, embedding, interface embeddingUnexported fields, internal/Hand-wiring in main, google/wire, uber-go/fxNo class inheritance; interfaces satisfied implicitly (Go FAQ: "Why is there no type inheritance?")
PHP 8.4 / Laravel 13Inheritance, traits, compositionprivate/protected, readonly, Eloquent accessorsService container, service providers, contextual bindingTraits copy code; contracts give interfaces
Java / SpringInheritance, composition, default interface methodsPackage-private, modulesSpring IoC container, constructor injectionClosest to the GoF book's setting
C# / .NETInheritance, extension methods, compositioninternalMicrosoft.Extensions.DependencyInjectionExtension methods add behaviour from outside
PythonMultiple inheritance, mixins, compositionNaming conventions, propertiesManual or dependency-injectorDuck typing replaces interfaces
TypeScriptClasses, structural interfacesprivate, module exportsNestJS, tsyringe, manualStructural typing like Go
RustTraits and composition, no inheritanceModule privacyManualComposition only

Mechanics ​

Finding violations and false alarms Must-know ​

In plain words: Search for chains, then judge each one by "is this a behaviour-bearing object whose structure may change?".

bash
# PHP / Laravel: three or more arrows on a model chain
grep -rnE '\$[a-z_]+(->[a-zA-Z_]+){3,}' app resources/views | head -50
# Go: three or more selectors on an identifier (data structs will show up too)
grep -rnE '\b[a-z][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){3,}' --include='*.go' . | head -50
ToolWhat it checksNotes
grep / rg with the patterns aboveCandidate chainsMany false positives (fluent builders, data)
Larastan / PHPStanTypes of each hop, nullable hopsReports property.nonObject when a hop can be null
golangci-lintStyle and nilness-type issuesNo Demeter linter in the default set
Code reviewWhose structure is being navigatedThe reliable one
CK metrics (CBO, RFC)Coupling between objects, response for a classBasili et al. 1996 link lower RFC to fewer bugs (via Wikipedia)

Go: method sets, shadowing and nil Important ​

RuleExampleConsequence
Promoted methods have the inner receiverd.Describe() runs Animal.DescribeNo virtual dispatch
Shallower depth winsDog.Speak shadows Animal.SpeakThe outer type "overrides" only for outside callers
Same depth is ambiguous when usedAB{A; B}.Hello()Compile error until you define AB.Hello
Embedded *T can be nilJob{} then job.PrintlnRuntime nil dereference
Embedded interface satisfied by the outer typestruct{ io.Writer } has WriteGreat for decorators; panics if the interface is nil
Wrapping loses optional interfacesA wrapper around http.ResponseWriter hides http.Flusher unless forwardedCheck http.NewResponseController (Go 1.20+)

PHP: trait precedence and container resolution Important ​

RuleDetail
PrecedenceClass members override trait methods, trait methods override inherited methods
ClashFatal error unless insteadof or as resolves it
Abstract methodsEnforce the host's contract; since 8.0 the signature must be compatible
PropertiesSame-name properties must be compatible; avoid trait state
StaticCall on the class using the trait, not the trait itself
ContainerAutowires typed constructor parameters; unresolvable primitives need when(...)->needs(...)->give(...) (contextual binding)

Go ​

Before ​

A function reaches through Order, Customer and Address. It breaks on nil, repeats the walk in two places and forces tests to build all three.

go
// Package before shows a train wreck: the caller walks the object graph
// Order -> Customer -> Address -> City and knows every type on the way.
package before

import "fmt"

type Address struct {
	Street string
	City   string
	Zone   string
}

type Customer struct {
	Name    string
	Address *Address
}

type Order struct {
	ID       int
	Customer *Customer
	Total    int // cents
}

// ShippingFee reaches through three objects. It depends on the shape of
// Order, Customer and Address, and it panics if any link is nil.
func ShippingFee(o *Order) int {
	if o.Customer.Address.City == "Tehran" {
		return 500
	}
	if o.Customer.Address.Zone == "remote" {
		return 2500
	}
	return 1200
}

// Label does the same walk again, in a second place.
func Label(o *Order) string {
	return fmt.Sprintf("%s, %s %s", o.Customer.Name, o.Customer.Address.Street, o.Customer.Address.City)
}
go
package before

import "testing"

// To test a fee rule we must build the whole graph, three levels deep.
func TestShippingFeeNeedsTheWholeGraph(t *testing.T) {
	o := &Order{
		ID:    1,
		Total: 9000,
		Customer: &Customer{
			Name:    "Sara",
			Address: &Address{Street: "Valiasr 1", City: "Tehran", Zone: "urban"},
		},
	}
	if got := ShippingFee(o); got != 500 {
		t.Fatalf("fee = %d, want 500", got)
	}
}

After ​

Order exposes ShipTo() (Hide Delegate) and ShippingLabel() (Tell Don't Ask). The fee rule takes a small Destination value and is tested with one struct.

go
// Package after applies Tell, Don't Ask and Hide Delegate: callers talk to
// Order only, and Order talks to its own direct components.
package after

import "fmt"

type address struct {
	street string
	city   string
	zone   string
}

// Destination is the small, stable view of an address that the rest of the
// system needs. Callers never see the address type.
type Destination struct {
	City   string
	Remote bool
}

type customer struct {
	name    string
	address address
}

type Order struct {
	ID       int
	Total    int
	customer customer
}

func NewOrder(id, total int, name, street, city, zone string) *Order {
	return &Order{ID: id, Total: total, customer: customer{name, address{street, city, zone}}}
}

// ShipTo is the one delegating method (Hide Delegate).
func (o *Order) ShipTo() Destination {
	return Destination{City: o.customer.address.city, Remote: o.customer.address.zone == "remote"}
}

// ShippingLabel is "tell": the order renders its own label.
func (o *Order) ShippingLabel() string {
	return fmt.Sprintf("%s, %s %s", o.customer.name, o.customer.address.street, o.customer.address.city)
}

// FeeCalculator only knows Destination, a value it receives as a parameter.
type FeeCalculator struct {
	Home       string
	HomeFee    int
	RemoteFee  int
	DefaultFee int
}

func (f FeeCalculator) Fee(d Destination) int {
	switch {
	case d.City == f.Home:
		return f.HomeFee
	case d.Remote:
		return f.RemoteFee
	default:
		return f.DefaultFee
	}
}
go
package after

import "testing"

// The rule is tested with a one-field value; no Order, Customer or Address.
func TestFeeNeedsOnlyADestination(t *testing.T) {
	f := FeeCalculator{Home: "Tehran", HomeFee: 500, RemoteFee: 2500, DefaultFee: 1200}
	cases := []struct {
		d    Destination
		want int
	}{
		{Destination{City: "Tehran"}, 500},
		{Destination{City: "Yazd", Remote: true}, 2500},
		{Destination{City: "Shiraz"}, 1200},
	}
	for _, c := range cases {
		if got := f.Fee(c.d); got != c.want {
			t.Errorf("Fee(%+v) = %d, want %d", c.d, got, c.want)
		}
	}
}

The Go angle ​

  • No inheritance, so composition is the language. The Go FAQ explains that Go has no type inheritance; types satisfy interfaces implicitly, so "interfaces can be added after the fact if a new idea comes along or for testing—without annotating the original types" (https://go.dev/doc/faq#inheritance).
  • Interfaces belong to the consumer. app.OrderStore lives in the package that uses it, with one method, so fakes are three lines.
  • Unexported fields enforce Demeter. In after, customer and address are unexported; callers cannot walk the graph even if they want to.
  • internal/ for module-level hiding (see SRP), and main as the composition root.
  • Standard library examples: bufio.ReadWriter (embedding), io.MultiWriter/io.TeeReader (composition of readers and writers), http.Handler plus http.HandlerFunc (middleware), http.StripPrefix (a decorator in the standard library).
  • Functional options (WithTimeout) and with-ers (Money.WithCents) keep values immutable and constructors stable.

Laravel ​

Before ​

A controller reads $order->customer->address->city. In a loop this is also 1 + 2N queries.

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;

// Before: the caller walks the Eloquent graph and knows every model on the way.
class ShippingLabelController
{
    public function show(Order $order): array
    {
        // Three dots, three models, three places where this can break:
        // a null customer, a null address, a renamed column.
        $city = $order->customer->address->city;

        $fee = $order->customer->address->zone === 'remote'
            ? 2500
            : ($city === 'Tehran' ? 500 : 1200);

        // In a loop this is also an N+1 query generator (see the SQL below).
        return [
            'name' => $order->customer->name,
            'line' => $order->customer->address->street.', '.$city,
            'fee'  => $fee,
        ];
    }
}

After ​

Order::shipTo() hides the walk, the shipping_label accessor tells the order to render itself, and FeeCalculator takes a Destination value. One loadMissing('customer.address') makes the query count explicit.

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

// After: Order is the only friend the caller needs. It answers questions
// and performs the work; the graph behind it can change without the caller noticing.
class Order extends Model
{
    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }

    // Hide Delegate: one method owns the walk through customer -> address.
    public function shipTo(): Destination
    {
        $address = $this->customer->address;

        return new Destination(city: $address->city, remote: $address->zone === 'remote');
    }

    // Tell, Don't Ask: the order renders its own label.
    protected function shippingLabel(): Attribute
    {
        return Attribute::get(fn () => $this->customer->name.', '.$this->customer->address->street.', '.$this->customer->address->city);
    }
}

// A small value the rest of the app depends on instead of Customer and Address.
final readonly class Destination
{
    public function __construct(public string $city, public bool $remote = false)
    {
    }
}

namespace App\Shipping;

use App\Models\Destination;

// The fee rule receives a value, not a graph. It is testable with new Destination('Yazd', true).
final class FeeCalculator
{
    public function __construct(private string $home = 'Tehran')
    {
    }

    public function fee(Destination $to): int
    {
        return match (true) {
            $to->city === $this->home => 500,
            $to->remote => 2500,
            default => 1200,
        };
    }
}

namespace App\Http\Controllers;

use App\Models\Order;
use App\Shipping\FeeCalculator;

class ShippingLabelController
{
    public function __construct(private FeeCalculator $fees)
    {
    }

    public function show(Order $order): array
    {
        // One eager load decides the query count, in one visible place.
        $order->loadMissing('customer.address');

        return ['line' => $order->shipping_label, 'fee' => $this->fees->fee($order->shipTo())];
    }
}

The Laravel angle ​

  • Eloquent relationship chains are the classic train wreck. $order->customer->address->city triggers lazy loading per hop. Eloquent's Model::preventLazyLoading(! $this->app->isProduction()) (documented under relationships) makes accidental lazy loads throw in development. That is a performance guard, not a design fix; the design fix is the method on Order.
  • Relationship shortcuts that are not violations. hasOneThrough / hasManyThrough define a relationship on the model that skips an intermediate table in SQL; callers still talk to one model. Choose it when the intermediate model is a pure join.
  • API Resources are the DTO layer: whenLoaded('customer') avoids lazy loads; the resource, not the controller, knows the shape.
  • Contracts and the container. Laravel's contracts are "a set of interfaces that define the core services provided by the framework". Depend on Illuminate\Contracts\Mail\Mailer rather than a concrete mailer; facades are convenient but hide the dependency, so prefer constructor injection in domain classes.
  • Pipeline and middleware give runtime composition; macros (Collection::macro) add behaviour to a framework class from outside ("macroable"). Declare them in a service provider's boot.
  • Traits such as SoftDeletes hook into Eloquent's lifecycle; do not use traits to share business rules that need test doubles.
  • Service providers are the composition root. register() binds, boot() runs after all providers are registered.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Model chain in controllers and viewsHide Delegate + value objectOrder::shipTo() returns DestinationOne place knows the pathA few more methods
Business rule in the callerTell Don't Askorder->markPaid()Invariants in one placeRisk of a god object; split by actor (SRP)
Deep inheritance treeReplace Inheritance with DelegationHold the parent as a field, forward needed methodsSwappable, testableForwarding boilerplate
Subclass per behaviour combinationDecorator or StrategyWrap objectsCombinations at runtimeMore objects to wire
new scattered in business codeConstructor injection + composition rootPass in interfacesFakes in testsWiring code grows
Hidden app() / facade callsInject the contractConstructor parameterDependencies visibleLonger constructors (a signal of too many duties)
Wrapper class that only forwardsRemove Middle ManExpose the collaborator or inject itLess indirectionCallers learn one more type
Shared mutable configImmutable value + with-ersreadonly class, value receiversThread-safe, predictableCopies
Cross-cutting code in every handlerMiddleware / PipelineCompose in one placeSingle point of changeOrder-dependent
Service reaching into another serviceEvent-carried state, API for the consumerPublish snapshotNo runtime hopData may be stale

Replace inheritance with delegation (worked move) ​

text
1   Before: class CachedRepo extends EloquentRepo { function find($id){ ...cache...; return parent::find($id); } }
2   Step A: introduce interface Repo { find($id) }; EloquentRepo implements Repo
3   Step B: class CachedRepo implements Repo { __construct(Repo $inner, Cache $c) }
4   Step C: CachedRepo::find() { return $c->remember(k, fn() => $inner->find($id)); }
5   Step D: bind Repo to new CachedRepo(new EloquentRepo, $cache) in the service provider
6   Result: tests of CachedRepo use a fake Repo; EloquentRepo no longer carries cache code

Choosing ​

SituationRecommendationExtra techniqueReason
Need to add logging/caching/retry around a serviceDecorator via compositionBind in provider / wire in mainCombinations at runtime
Real is-a relationship, stable, Liskov holdsInheritance is fineKeep hierarchy shallowSubstitutability
Framework requires a base class (Model, Controller)Inherit, but keep logic out of itPut rules in injected objectsYou cannot avoid the extension point
Sharing three helper methods between unrelated classesTrait (PHP) / embedding (Go)Keep statelessCheapest reuse
Sharing code that has state or rules that changeInject a collaboratorInterface at the consumerTest double, swap
Caller needs a nested valueHide Delegate, return a value objectDestination-style typeNarrow dependency
Plain data record read by manyAllow the chainPass sub-structs to narrowData is its own interface
Wrapper has 15 forwarding methodsRemove Middle ManInject the collaboratorLess indirection
Need many views of related dataAPI Resource / BFF / read modelEager load onceOne place knows the shape
Cross-service data needEvent-carried stateInbox, idempotent upsertNo chain of calls

In architecture: from a single process to a distributed system ​

The same two questions scale: "what do I hold?" and "how far do I see?". At every level the answer is "only the interfaces of my direct collaborators".

Monolith: one process, one database ​

How it shows up: classes in folders; Eloquent models reaching through each other; controllers that know four models; base classes with logic in them.

Simplest correct usage: one composition root (service providers), constructor injection of contracts, domain methods on models (shipTo()), API Resources as DTOs, preventLazyLoading on in development.

Example (simple): a blog: PostController receives a PostPublisher action; Post::excerpt() instead of $post->body->text->first(200).

Example (production): a shop where Order exposes shipTo(), total(), markPaid(); FeeCalculator, TaxCalculator, Notifier are injected; a Pipeline prices a cart (coupon, shipping, tax) and each stage is replaceable.

Modular monolith and multiple databases ​

How it shows up: modules own their tables and expose a facade; Demeter is the rule between modules. A module's internal models are strangers to every other module.

sql
-- PostgreSQL: another module sees a view, not tables (the view is the published contract).
CREATE SCHEMA shipping;
CREATE VIEW shipping.order_destinations AS
  SELECT o.id AS order_id, a.city, (a.zone = 'remote') AS remote
  FROM orders.orders o
  JOIN customers.addresses a ON a.customer_id = o.customer_id;
GRANT SELECT ON shipping.order_destinations TO shipping_app;
-- shipping_app never reads orders.* or customers.*; if the join changes, only the view changes.

Rules: other modules call Orders::shipTo($id) or read the view; architecture tests (Deptrac, PHPArkitect for PHP; go list -deps or internal/ for Go) fail the build when one module imports another's internals; each module has its own service provider as its composition root.

Microservices: LoD with a network boundary ​

What survives: composition (each service is a component with an interface) and Demeter (talk to your direct neighbours' contracts). What breaks: if a service reaches through another's data model, a field rename is now a multi-team release.

text
     Checkout flow: "show delivery city on the order page"
1    Wrong: web -> orders -> customers -> addresses          (3 hops, 3 teams, 3 timeouts)
2    Better: orders publishes OrderPlaced{shipTo.city}; shipping and web read their own copies
3    Or: BFF calls orders.GetOrderView(id) which returns the assembled view designed for that page

Example: orchestration (Tell Don't Ask) with a saga orchestrator telling payment and stock services what to do; versus choreography where each reacts to OrderPlaced. Both keep any service from navigating another's storage. Publishing reliably needs an outbox.

PatternLoD reading
API Gateway / BFFThe one place that composes many services for a client (gateway chapter)
Anti-Corruption LayerA Hide Delegate for a foreign model
Event-carried statePublisher decides what friends may know
Shared databaseEveryone is a friend of every table: the worst violation

Distributed data: replicas, caches and shared schemas ​

Where the law breaks: a cache that stores serialized object graphs makes every reader depend on the graph shape; a read replica queried with arbitrary joins couples every team to the schema; an event that contains a whole entity ($order->toArray()) publishes internals.

Countermeasures: cache small, purpose-built values (shipping:city:{orderId}), version event schemas (message design), expose read models instead of replicas, never serialize ORM models into events.

Scaling path: 1×, 10×, 100× ​

ScaleStructureComposition / Demeter practice
1× (one team, one app)Folders by featureConstructor injection, domain methods on models, no logic in base classes
10× (several teams, one repo)Modular monolithModule facades, views as contracts, per-module providers, architecture tests
100× (many teams, many services)Services per capabilityPublished events and APIs designed for consumers, BFF, no shared tables, contract tests

Lab ​

You will reproduce a train wreck, measure its cost, and fix it. Everything runs offline.

Setup.

bash
cd docs/snippets/design/composition-law-of-demeter/go
gofmt -l . && go vet ./... && go test ./...      # everything compiles, vet is clean

Step 1: count what a test must build.

bash
grep -c '&Customer\|&Address' chain/before/order_test.go chain/after/order_test.go
# chain/before/order_test.go: 2   (Customer and Address are constructed)
# chain/after/order_test.go:  0

Step 2: prove the walk is fragile. In chain/before/order.go, rename Address.City to Town. Expected: go build ./chain/before fails in two places (ShippingFee and Label). Now do the same in chain/after/order.go (field city to town): only ShipTo and ShippingLabel inside the type change; no caller edits.

Step 3: prove embedding is not inheritance.

bash
go run ./embedding
# Rex barks
# I am Rex; Rex makes a sound     <- Describe did not call Dog.Speak

Step 4: swap a collaborator in a test. Open root/app/service_test.go; note there is no database and no SMTP. Add a failing store (err: boom) and check that no mail is sent (already in the second test).

Step 5: build a middleware chain.

bash
go test ./middleware -run TestChainOrderAndShortCircuit -v
# --- PASS: TestChainOrderAndShortCircuit

Step 6 (Laravel, optional). Put ChainBefore.php in a scratch app with two seeded relations and run DB::enableQueryLog() for 50 orders: expect 101 queries. Apply ChainAfter.php and Order::with('customer.address'): expect 3.

MetricBeforeAfter
Types a fee test builds3 (Order, Customer, Address)1 (Destination)
Places edited when City is renamed2 or more callers1 type
Queries for 50 orders (Eloquent)1013
Nil panics possible in caller2 (customer, address)0 (inside the owner)

Common misconceptions ​

BeliefReality
"Composition replaces inheritance everywhere"Favour it; use inheritance for true is-a that respects LSP
"Go embedding is inheritance"Promoted methods keep the inner receiver; there is no virtual dispatch
"Traits are composition"Traits copy code into the class and share its $this; they cannot be swapped or faked
"One dot per line is the Law of Demeter"The law is about whose methods you call; the dot count only flags candidates
"Fluent builders violate the law"A builder returns itself; you talk to one friend. The 1988 paper allows chains of constructor calls
"Reading a DTO's fields violates the law"Plain data records are their own interface; narrow what you pass instead
"Follow the law by adding a wrapper for every field"That creates a Middle Man; hide only what callers really use
"A DI container is dependency injection"Injection is passing arguments; the container only automates it
"app() inside a class is fine, it is just injection"That is a service locator; the dependency is hidden
"Eager loading fixes the Demeter violation"It fixes queries; the chain and its coupling remain
"Microservices are loosely coupled by default"A service that walks other services' data is a distributed train wreck
"Immutable objects are slow"Small value copies are cheap and prevent shared-state bugs

Cheat sheet ​

TopicWhat to remember
CompositionHas-a, via interface, assembled at construction; favour it
InheritanceOnly for stable is-a that is substitutable
DelegationAsk a held helper to do part of the job
ForwardingPass-through wrapper; the inner this stays inner
Go embeddingPromotion, inner receiver, no virtual dispatch
Interface embeddingBuild bigger contracts from one-method ones
PHP traitsCode copy; insteadof / as; abstract methods for needs; avoid state
Constructor injectionRequired collaborators as parameters
Composition rootOne place builds the graph (main, service provider)
Friendsself, parameters, created objects, direct components (globals discouraged)
One dotA smell detector, not the rule
ExceptionsFluent builders, value chains, plain data
Tell Don't AskMove decisions to the data's owner
Hide DelegateDomain-named method that hides the walk
Middle ManIf most methods only forward, remove it
With-ers / optionsImmutable copies; functional options for constructors
Pipeline / middlewarefunc(Handler) Handler, $next($input), order matters
Across servicesConsume contracts and events, never another service's tables

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does Dog.Describe() in Go print "Rex makes a sound" even though Dog defines Speak? Important ​

Answer

Answer: The promoted method runs with the inner Animal as receiver, so Animal.Speak is called. Embedding forwards; it does not dispatch virtually. See Go embedding.

2 — Name the friends of a method under the Law of Demeter. Must-know ​

Answer

Answer: The object itself, the method's parameters, objects created in the method, the object's direct components, and (in the original) globals. See LoD precisely.

3 — Is $users->map(...)->filter(...)->sum() a violation? Important ​

Answer

Answer: No. It is a collection pipeline over values; each call returns a new collection of the same kind. See Exceptions.

4 — Why are PHP traits not composition? Important ​

Answer

Answer: They copy methods and state into the host class; they share $this, cannot be swapped at runtime or replaced with a fake. See PHP traits.

5 — What is the composition root and where is it in Laravel? Important ​

Answer

Answer: The single place that builds the object graph. In Laravel: service providers and bootstrap/app.php; in Go: main. See Object graph assembly.

6 — When is Hide Delegate a mistake? Good to know ​

Answer

Answer: When it produces many pass-through methods; that is a Middle Man. Hide only what callers use, with domain names. See Middle Man.

7 — How does Tell Don't Ask relate to the Law of Demeter? Must-know ​

Answer

Answer: Telling the owner what to do removes the need to fetch its parts, so the caller has fewer friends. See Tell Don't Ask.

8 — Does preventLazyLoading fix a Demeter violation? Important ​

Answer

Answer: No. It makes accidental lazy loading fail loudly; the chain and its coupling remain. Add a method on the owning model. See Laravel angle.

9 — What is the service-level version of a message chain? Important ​

Answer

Answer: A service calling several services in sequence to assemble a fact, or reading another service's tables. Fix with event-carried state or an API designed for the consumer. See Across services.

10 — Why do tests get easier with composition? Must-know ​

Answer

Answer: The test builds only the declared interfaces (small fakes), not the whole graph. See Why tests get easier.

Glossary ​

TermMeaning
CompositionBuilding behaviour from objects an object holds
InheritanceDefining a class in terms of a parent class
Is-a / Has-aSubtype relation vs holding relation
DelegationHanding part of the work to a held helper
ForwardingA wrapper passing a call unchanged to the inner object
Virtual dispatchChoosing the method by the runtime type of the receiver
Fragile base classA parent change that breaks subclasses
Embedding (Go)A field with a type and no name; methods are promoted
Method promotionInner type's methods appear on the outer type
Interface embeddingAn interface listing other interfaces
Trait (PHP)Group of methods copied into classes with use
insteadof / asTrait conflict resolution and alias operators
Abstract trait methodA method the host class must implement
Constructor injectionPassing dependencies as constructor arguments
Service locatorFetching dependencies from a global registry inside the class
DI containerA tool that builds objects and injects their dependencies
Composition rootThe place where the object graph is assembled
Law of DemeterA method talks only to its friends
FriendSelf, parameter, created object, direct component
StrangerAn object obtained from a friend's return value
Message chain / train wrecka.b().c().d() navigation
Tell, Don't AskCommand objects instead of pulling their data
Hide DelegateRefactoring that adds a method hiding a walk
Middle ManClass that mostly forwards
Fluent interfaceAPI designed to read as a chain on one object
DTOData transfer object with no behaviour
With-erMethod returning a modified copy
Functional optionFunction that configures a constructor
Pipeline / middlewareChain of handlers composed at runtime
Orchestration / choreographyCentral coordinator vs events between services
Event-carried state transferEvent contains the data consumers need
Anti-Corruption LayerAdapter that shields a model from a foreign one

References ​

Built by Morteza Negahi