RDM LABSPORTUGUÊS

Technical article/ · 9 min read

Classic design patterns inside Laravel

Laravel Saga · Season 0 · Episode 08

Let me start by clearing up a common misunderstanding: design patterns aren't ready-made code to copy and paste. They're vocabulary. When someone on your team says "this is a Strategy", everyone understands the structure of the solution without drawing anything on the whiteboard. It's like musicians talking about a "chord progression": a short name for a whole idea.

The most famous catalogue is the 1994 book Design Patterns, written by four authors who became known as the Gang of Four (GoF). It organises 23 patterns into three families:

FamilyQuestion it answersExamples
CreationalHow do we create objects?Factory Method, Abstract Factory, Builder, Singleton
StructuralHow do we compose objects?Adapter, Facade, Decorator, Proxy
BehaviouralHow do objects collaborate?Strategy, Observer, Chain of Responsibility, Template Method

Besides the GoF, there's another catalogue that matters a lot to anyone working on the web: Martin Fowler's, in Patterns of Enterprise Application Architecture, from 2002. That's where the Front Controller, Active Record, Data Mapper and Repository come from.

Today I won't show you abstract diagrams with classes called ConcreteCreatorA. Instead, let's do something more fun: find each pattern inside Laravel.

Front Controller

The problem: if every URL were a different PHP file, all the shared logic (authentication, session, error handling) would be scattered across hundreds of files.

The solution: a single entry point receives every request and delegates the work.

Where it lives in Laravel: in public/index.php. Remember NGINX's try_files, in episode 02? It sends every URL to that file. And that's where everything shared happens: the boot, the middleware, the exception handling.

Strategy

The problem: an algorithm has several variations, and you want to choose between them without filling the code with ifs.

The solution: each variation becomes a class that implements the same interface, and the code that uses it talks only to the interface.

Where it lives in Laravel: in the drivers. Cache, session, queue, mail, filesystem, hashing and logging all follow this pattern. Look how neat it is:

php// Your code is always the same...
Cache::put('ranking', $ranking, now()->addHour());
dotenv# ...and the strategy changes only through configuration
CACHE_STORE=redis      # or database, file, memcached, array

Under the hood, RedisStore, DatabaseStore, FileStore and ArrayStore implement the same contract, Illuminate\Contracts\Cache\Store. And you know when you use the array driver in tests? You're simply switching strategy.

Factory and the Manager pattern

The problem: which object to create depends on configuration, and you don't want that decision scattered across the code.

The solution: a factory centralises creation.

Where it lives in Laravel: in the Manager classes, such as CacheManager, QueueManager, MailManager and FilesystemManager. In practice, they're factories of strategies: they read the configuration, create the right driver and keep the instance to reuse it.

phpCache::store('redis')->get('key');   // the CacheManager creates or reuses the redis driver
Storage::disk('s3')->put('a.txt', 'contents');

// Registering a new strategy without editing the framework (remember Open/Closed?)
Cache::extend('mongo', function ($app) {
    return Cache::repository(new MongoStore($app['mongo']));
});

Putting the two patterns together, the path of a cache call looks like this:

Strategy and Manager in the cacheCache::put() to CacheManager: asks for the store. CacheManager to RedisStore: redis. CacheManager to DatabaseStore: database. CacheManager to FileStore: file. CacheManager to ArrayStore: array. Scenario redis. CACHE_STORE=redis. The manager creates the RedisStore once and reuses the instance on later calls. Path: Cache::put(), CacheManager, RedisStore. Scenario database. CACHE_STORE=database. The same call writes to a database table, without changing a line of your code. Path: Cache::put(), CacheManager, DatabaseStore. Scenario file. CACHE_STORE=file. Values go to files in storage/framework/cache. Path: Cache::put(), CacheManager, FileStore. Scenario array. CACHE_STORE=array, the default in tests. Everything stays in memory and disappears when the process ends. Path: Cache::put(), CacheManager, ArrayStore.Cache::put()your codeCacheManagerreads CACHE_STORERedisStoreproductionDatabaseStoreno RedisFileStorelocal diskArrayStoretestsasks for the storeredisdatabasefilearrayCache::put()your codeCacheManagerreads CACHE_STORERedisStoreproductionasks for the storeredisCache::put()your codeCacheManagerreads CACHE_STOREDatabaseStoreno Redisasks for the storedatabaseCache::put()your codeCacheManagerreads CACHE_STOREFileStorelocal diskasks for the storefileCache::put()your codeCacheManagerreads CACHE_STOREArrayStoretestsasks for the storearray
Strategy and Manager in the cacheCache::put() to CacheManager: asks for the store. CacheManager to RedisStore: redis. CacheManager to DatabaseStore: database. CacheManager to FileStore: file. CacheManager to ArrayStore: array. Scenario redis. CACHE_STORE=redis. The manager creates the RedisStore once and reuses the instance on later calls. Path: Cache::put(), CacheManager, RedisStore. Scenario database. CACHE_STORE=database. The same call writes to a database table, without changing a line of your code. Path: Cache::put(), CacheManager, DatabaseStore. Scenario file. CACHE_STORE=file. Values go to files in storage/framework/cache. Path: Cache::put(), CacheManager, FileStore. Scenario array. CACHE_STORE=array, the default in tests. Everything stays in memory and disappears when the process ends. Path: Cache::put(), CacheManager, ArrayStore.Cache::put()your codeCacheManagerreads CACHE_STORERedisStoreproductionDatabaseStoreno RedisFileStorelocal diskArrayStoretestsasks for the storeredisdatabasefilearrayCache::put()your codeCacheManagerreads CACHE_STORERedisStoreproductionasks for the storeredisCache::put()your codeCacheManagerreads CACHE_STOREDatabaseStoreno Redisasks for the storedatabaseCache::put()your codeCacheManagerreads CACHE_STOREFileStorelocal diskasks for the storefileCache::put()your codeCacheManagerreads CACHE_STOREArrayStoretestsasks for the storearray

redis

CACHE_STORE=redis. The manager creates the RedisStore once and reuses the instance on later calls.

database

CACHE_STORE=database. The same call writes to a database table, without changing a line of your code.

file

CACHE_STORE=file. Values go to files in storage/framework/cache.

array

CACHE_STORE=array, the default in tests. Everything stays in memory and disappears when the process ends.

Strategy and Manager in the cache

Eloquent also has model factories for tests, as in User::factory()->count(10)->create(). That's the factory pattern applied directly.

Adapter

The problem: you want to use a library whose interface doesn't match the one your code expects.

The solution: an intermediate class "translates" one interface into the other, like a plug adapter.

Where it lives in Laravel: in the filesystem, which uses Flysystem. It has adapters for the local disk, S3, FTP, SFTP and others. Each adapter translates generic operations (write, read, delete) into the specific API of each service.

phpStorage::disk('local')->put('report.pdf', $pdf);
Storage::disk('s3')->put('report.pdf', $pdf);   // the same call, a completely different API underneath

Mail transports (SMTP, Mailgun, Postmark, SES) follow the same idea. And hold on to this pattern: in episode 10, you'll see that AI SDKs that talk to several providers use exactly the Adapter to hide the differences between the APIs.

Facade: the book's pattern and Laravel's Facade

This one deserves extra attention, because the name is misleading.

The GoF pattern: a Facade is a simple interface in front of a complex subsystem. Instead of dealing with ten classes, you talk to one.

php// Facade in the GoF sense
final class VideoConverter
{
    public function convert(string $file, string $format): string
    {
        $codec = (new CodecFactory())->extract($file);
        $buffer = (new BitrateReader())->read($file, $codec);
        $result = (new AudioMixer())->fix($buffer);

        return (new Encoder())->encode($result, $format);
    }
}

Laravel's Facade is something else. It's a class with a static interface that forwards each call to an object living in the container:

phpCache::get('key');
// is the same as
app('cache')->get('key');

That's why many authors say Laravel's Facades look more like a static Proxy, or like the Service Locator we saw in the previous episode, than like the GoF Facade. The name was a historical choice by the framework. There's nothing wrong with that, but it's worth understanding the difference so you don't get confused when reading about patterns.

Chain of Responsibility and Pipeline

The problem: a request has to go through several steps, and each step may handle it, modify it or stop it.

The solution: chain handlers together, and each one decides whether to pass the request along.

Where it lives in Laravel: in middleware. Each middleware receives the request and a closure called $next:

phppublic function handle(Request $request, Closure $next): Response
{
    if (! $request->user()) {
        return redirect('/login');   // breaks the chain
    }

    return $next($request);          // passes it along
}
Each middleware decides whether to pass it alongRequest to StartSession: enters. StartSession to Authenticate: $next. Authenticate to ValidateCsrfToken: $next. ValidateCsrfToken to Controller: $next. Authenticate to /login: no user. Scenario Logged in. Each middleware does its part and calls $next. The request goes through the whole chain to the controller. Path: Request, StartSession, Authenticate, ValidateCsrfToken, Controller. Scenario Not logged in. Authenticate finds no user and returns the redirect. The chain stops there: the controller never hears about it. Path: Request, StartSession, Authenticate, /login.Requestfrom index.phpStartSessionmiddlewareAuthenticatemiddlewareValidateCsrfTokenmiddlewareControlleryour action/loginredirectenters$next$next$nextno userRequestfrom index.phpStartSessionmiddlewareAuthenticatemiddlewareValidateCsrfTokenmiddlewareControlleryour actionenters$next$next$nextRequestfrom index.phpStartSessionmiddlewareAuthenticatemiddleware/loginredirectenters$nextno user

Logged in

Each middleware does its part and calls $next. The request goes through the whole chain to the controller.

Not logged in

Authenticate finds no user and returns the redirect. The chain stops there: the controller never hears about it.

Each middleware decides whether to pass it along

And the Illuminate\Pipeline\Pipeline class generalises this idea to any context. You can use it in your own code:

phpuse Illuminate\Support\Facades\Pipeline;

$text = Pipeline::send($rawText)
    ->through([
        RemoveHtml::class,
        NormalizeWhitespace::class,
        CensorBadWords::class,
    ])
    ->thenReturn();

If I could single out one pattern from this episode for you to take into the saga, it would be this one. The lifecycle of a request in Laravel is, essentially, two chained pipelines. When we get there, you'll remember this paragraph.

Observer

The problem: when something happens, several parts of the system need to react, but whoever triggers the event shouldn't know who reacts.

The solution: a "subject" notifies a list of "observers" that have subscribed.

Where it lives in Laravel: in events and listeners, and also in model observers.

php// Whoever dispatches doesn't know who is listening
event(new OrderPaid($order));

// Independent listeners react
class SendReceipt     { public function handle(OrderPaid $event) { /* email */ } }
class UpdateInventory { public function handle(OrderPaid $event) { /* stock */ } }
class NotifyFinance   { public function handle(OrderPaid $event) { /* Slack */ } }
phpuse Illuminate\Database\Eloquent\Attributes\ObservedBy;

#[ObservedBy(PostObserver::class)]
class Post extends Model {}

class PostObserver
{
    public function created(Post $post): void { /* ... */ }
    public function deleting(Post $post): void { /* ... */ }
}

A warning from someone who has suffered with this: the Observer reduces coupling, but makes the flow less visible. If saving a post triggers five side effects hidden in observers, good luck debugging. Use it for real side effects, not for the main business rule.

Template Method

The problem: an algorithm has a fixed structure, but some steps vary.

The solution: a base class defines the skeleton and calls methods that subclasses override.

Where it lives in Laravel: in the Form Request. The base class controls the order (prepare, authorise, validate, finish), and you only fill in the "hooks":

phpclass StorePostRequest extends FormRequest
{
    protected function prepareForValidation(): void { /* step 1 */ }
    public function authorize(): bool { /* step 2 */ }
    public function rules(): array { /* step 3 */ }
    protected function passedValidation(): void { /* step 4 */ }
}

The ServiceProvider (first register, then boot), the Command (with its handle) and the Model lifecycle events follow the same principle.

Builder

The problem: building a complex object takes many optional steps, and a constructor with ten parameters is unreadable.

The solution: an object accumulates the configuration step by step and only delivers the result at the end.

Where it lives in Laravel: in the Query Builder and the Eloquent Builder.

php$posts = Post::query()
    ->where('status', PostStatus::Published)
    ->whereHas('tags', fn ($query) => $query->where('slug', 'laravel'))
    ->with('author')
    ->latest('published_at')
    ->limit(10)
    ->get();   // only here is the query actually executed

Notice that each method returns the builder itself (this is called a fluent interface), and only the final get() produces the result. The Http:: client, mail messages and the task scheduler follow the same style.

Active Record versus Data Mapper

Here we have two patterns that solve the same problem in opposite ways, and understanding the difference explains a lot about Laravel's personality.

In Active Record, each object represents a row in the table and knows how to save itself:

php$post = new Post(['title' => 'Hello']);
$post->save();                          // the object itself goes to the database
$post = Post::find(42);
$post->delete();

In Data Mapper, domain objects know nothing about the database. A separate mapper takes care of persistence:

php// Doctrine style
$post = new Post('Hello');
$entityManager->persist($post);
$entityManager->flush();

Eloquent is Active Record. The big advantage is productivity and readability. The cost is that the model mixes domain with persistence, and business rule tests end up depending on the database. Doctrine, used by Symfony, is Data Mapper: more flexible for complex domains, but with a lot more ceremony.

Neither one is "the right one". It's a trade-off, and Laravel's choice of Active Record says a lot about the framework's philosophy: productivity first.

What about the Repository?

The Repository pattern hides data access behind an interface that behaves like a "collection":

phpinterface PostRepository
{
    public function findPublished(int $limit): Collection;
    public function save(Post $post): void;
}

In the Laravel world, this pattern is controversial, and I think it's important you know both sides. With Data Mapper, it makes a lot of sense. With Active Record, many people consider it redundant, because Eloquent is already a data access abstraction. Repositories that just pass calls through (find, create, update) add layers without bringing any benefit.

It starts to pay off when you have complex queries that need to be centralised, several data sources or a domain you want to isolate from Eloquent. This discussion comes back in the next episode.

Decorator

The problem: adding behaviour to an object without touching its class.

The solution: wrap the object in another one, with the same interface, that does something before or after delegating.

phpfinal class CachedExchangeRates implements ExchangeRates
{
    public function __construct(private ExchangeRates $inner) {}

    public function rate(string $from, string $to): float
    {
        return Cache::remember("rate:{$from}:{$to}", 3600, fn () => $this->inner->rate($from, $to));
    }
}

Laravel's container lets you decorate any service with $this->app->extend():

php$this->app->extend(ExchangeRates::class, fn ($service) => new CachedExchangeRates($service));

Notice the elegance: whoever uses ExchangeRates now gets caching, and not a single line of those classes had to change.

What about the Singleton?

The classic GoF Singleton, the one with a private constructor and a static getInstance() method, is now seen as an anti-pattern. It hides dependencies and makes testing harder.

Laravel meets the same need ("I want a single instance") in a much better way: with $app->singleton(). Whoever decides there will be a single instance is the container, not the class. The class remains an ordinary class, testable and injectable. See how the previous episode connects to this one?

The map: where each pattern lives

PatternWhere it shows up in Laravel
Front Controllerpublic/index.php
StrategyCache, queue, session, mail and filesystem drivers
Factory / ManagerCacheManager, QueueManager, model factories
AdapterFlysystem, mail transports
Facade (GoF)Simplified APIs, such as Http:: and Mail::, over subsystems
Static Proxy / Service LocatorLaravel's Facades and the app() helper
Chain of Responsibility / PipelineMiddleware and the Pipeline class
ObserverEvents, listeners and model observers
Template MethodForm Request, Service Provider, Command
BuilderQuery Builder and Eloquent Builder
Active RecordEloquent
Decorator$app->extend()
IoC / DIService Container

What to take into the saga

  • Patterns are vocabulary for recurring solutions, not code to copy.
  • Laravel is a collection of well-combined patterns: Strategy + Manager in the drivers, Pipeline in the lifecycle and Active Record in Eloquent.
  • Laravel's Facade isn't the GoF Facade; it's a static proxy to the container.
  • Active Record trades domain purity for productivity, and the Repository is optional and debated.

Next episode

Patterns solve local design problems involving a few classes. But what about when the question is about the entire application? Does MVC cut it? When is it worth thinking about layers, hexagonal architecture, DDD or microservices?

In the next episode, we'll go up a level and talk about software architecture. And I'll be very honest about when each approach is worth it, and when it only adds complexity. See you in episode 09.

References and further reading

Online catalogues

The patterns in Laravel

Books

  • Design Patterns: Elements of Reusable Object-Oriented Software, by Gamma, Helm, Johnson and Vlissides (Addison-Wesley). The original Gang of Four book.
  • Head First Design Patterns, by Eric Freeman and Elisabeth Robson (O'Reilly). The most approachable way into the subject.
  • Patterns of Enterprise Application Architecture, by Martin Fowler (Addison-Wesley).