RDM LABSPORTUGUÊS

Technical article/ · 9 min read

Software architecture: from layers to styles

Software architecture: from layers to styles

Laravel Saga · Season 0 · Episode 09

In the previous episode, we looked at patterns that solve problems involving a few classes. Today we'll go up a level and look at the entire application: how it's divided, how the parts talk to each other and which decisions will be hard to change in the future.

First of all, I want to give you the definition of architecture that has helped me most in practice: architecture is the set of decisions that are expensive to reverse. Renaming a variable is cheap. Switching databases, splitting a monolith into services or changing how the business rules talk to the infrastructure is expensive. It's that second kind of decision we're going to talk about.

And a heads-up: this episode has more "it depends" than the previous ones. Architecture is, essentially, the art of choosing trade-offs.

MVC: the starting point

MVC (Model-View-Controller) was born in Smalltalk, at the end of the 1970s, for desktop graphical interfaces. On the web, it got an adapted version:

MVC on the webRequest to Controller: route. Controller to Model: queries. Controller to View: hands over the data. View to Response: HTML or JSON.RequestinputControllercoordinatesModeldata and rulesViewpresentationResponseoutputroutequerieshands over the dataHTML or JSON
MVC on the webRequest to Controller: route. Controller to Model: queries. Controller to View: hands over the data. View to Response: HTML or JSON.RequestinputControllercoordinatesModeldata and rulesViewpresentationResponseoutputroutequeriesdataHTML or JSON
MVC on the web
LayerResponsibilityIn Laravel
ModelData and business rulesEloquent models
ViewPresentationBlade, Inertia (React/Vue), Livewire
ControllerReceives the input, coordinates and returns the responseControllers

MVC solves the most basic problem of all: not mixing HTML, SQL and business rules in the same file. That's already a lot.

But it doesn't answer a question that will show up in your life sooner or later: where do I put a rule that involves three models, an external API and an email? Without a clear answer, projects tend to slide towards one of these two extremes:

  • Fat controller: the controller does everything, with three hundred lines per method.
  • Fat model: the model accumulates all the logic and becomes a two-thousand-line class.

If you've ever opened a project like that, you know the feeling. That's why applications that grow need a bit more structure than MVC offers.

Layered architecture

Layered architecture divides the application by technical responsibility, with a simple rule: each layer only depends on the layer below it.

Each layer only depends on the one belowPresentation to Application: calls the use case. Application to Domain: applies the rules. Domain to Infrastructure: persists and integrates.PresentationControllers, ResourcesApplicationActions, ServicesDomainrules, entities, enumsInfrastructuredatabase, queues, APIsuse caserulespersists
Each layer only depends on the one below

In Laravel, it usually ends up roughly like this:

php// Presentation: translates HTTP into the use case, and back
class OrderController
{
    public function store(StoreOrderRequest $request, PlaceOrder $placeOrder)
    {
        $order = $placeOrder->handle($request->user(), $request->toCartData());

        return OrderResource::make($order)->response()->setStatusCode(201);
    }
}

// Application: a use case that knows nothing about HTTP
class PlaceOrder
{
    public function __construct(
        private PaymentGateway $payments,
        private Dispatcher $events,
    ) {}

    public function handle(User $customer, CartData $cart): Order
    {
        return DB::transaction(function () use ($customer, $cart) {
            $order = Order::createFromCart($customer, $cart);
            $this->payments->charge($order->total(), $cart->paymentToken);
            $this->events->dispatch(new OrderPlaced($order));

            return $order;
        });
    }
}

A detail an attentive reader will notice: PlaceOrder receives the gateway and the event dispatcher through injection, but uses the DB::transaction() facade. It's a pragmatic concession, common in Laravel projects. If you want to be strict, inject the Illuminate\Database\ConnectionInterface contract and call $this->db->transaction(...). The behaviour is the same; the difference is that the database dependency now shows up in the constructor.

Want a quick test to see whether your separation is good? Ask yourself: can PlaceOrder be called from a controller, an Artisan command, a job or a test, without changing anything? If your business rule only works inside an HTTP request, it's in the wrong layer.

Hexagonal Architecture (Ports and Adapters)

Hexagonal architecture, proposed by Alistair Cockburn, changes the way the layers are drawn. Instead of "top and bottom", it thinks in terms of inside and outside:

Input adapters, domain, ports and output adaptersHTTP Controller to Domain. CLI Command to Domain. Queue Job to Domain. Domain to PaymentGateway. Domain to OrderRepository. Domain to Mailer. PaymentGateway to StripeGateway. OrderRepository to EloquentOrderRepository. Mailer to SesMailer.HTTP Controllerinput adapterCLI Commandinput adapterQueue Jobinput adapterDomainrules and use casesPaymentGatewayoutput portOrderRepositoryoutput portMaileroutput portStripeGatewayoutput adapterEloquentOrderRepositoryoutput adapterSesMaileroutput adapter
Input adapters, domain, ports and output adaptersHTTP Controller to Domain. CLI Command to Domain. Queue Job to Domain. Domain to PaymentGateway. Domain to OrderRepository. Domain to Mailer. PaymentGateway to StripeGateway. OrderRepository to EloquentOrderRepository. Mailer to SesMailer.HTTP Controllerinput adapterCLI Commandinput adapterQueue Jobinput adapterDomainrules and use casesPaymentGatewayoutput portOrderRepositoryoutput portMaileroutput portStripeGatewayoutput adapterEloquentOrderRepositoryoutput adapterSesMaileroutput adapter
Input adapters, domain, ports and output adapters

There are only a few concepts:

  • Ports are interfaces defined by the domain (PaymentGateway, OrderRepository).
  • Adapters are the technical implementations that plug into those ports (StripeGateway, EloquentOrderRepository).
  • The domain doesn't know any adapter. It only knows the ports.

And now notice something beautiful: none of this is new to you. It's the Dependency Inversion Principle from episode 06 and the Adapter pattern from episode 08, applied to the whole application. And who wires each port to its adapter? The container from episode 07. The episodes are clicking into place.

Clean Architecture and Onion Architecture

Robert C. Martin's Clean Architecture and Jeffrey Palermo's Onion Architecture are variations of the same idea, drawn as concentric circles:

Frameworks and driverswhat comes from outside
  • Laravel
  • MySQL
  • Redis
Adapterstranslate inwards
  • controllers
  • gateways
  • repositories
Use caseswhat the application does
  • PlaceOrder
  • CancelOrder
Entitiesthe domain
  • Order
  • Money
  • Email
Code only points inwards

The central rule is called the dependency rule: code can only point inwards. The domain doesn't know Laravel exists.

Now, let me be frank with you. Applying this rigidly in Laravel has a high cost: giving up Eloquent in the domain, writing mappers, duplicating structures. I've seen small projects drown in layers that didn't need to exist. For most applications, a pragmatic version works better: isolated use cases, interfaces for external integrations and Eloquent accepted as part of the domain.

Domain-Driven Design (DDD)

DDD, introduced by Eric Evans in 2003, is often mistaken for a folder structure. But it's, above all, about modelling the business. And its most valuable concepts are precisely the least technical ones:

  • Ubiquitous language: the code uses the same words as the business people. If finance says "invoice", the class is called Invoice, not BillingDocument.
  • Bounded contexts: the same word can mean different things in different areas. "Customer" in sales (lead, sales funnel) isn't the same "Customer" in finance (overdue payments, credit limit).

Then come the tactical concepts:

ConceptWhat it isExample
EntityHas an identity that persists over timeOrder with id 42
Value ObjectDefined only by its value, immutableMoney, Email, Address
AggregateA group of objects with a root that guarantees consistencyOrder and its OrderItems
Domain eventSomething relevant that happened in the businessOrderPlaced

If you want to start applying some DDD tomorrow, start with value objects. A simple example already makes a difference:

phpfinal readonly class Email
{
    public string $value;

    public function __construct(string $value)
    {
        if (! filter_var($value, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException("Invalid email: {$value}");
        }

        $this->value = strtolower($value);
    }
}

From then on, anywhere that receives an Email, you know it's valid. No need to validate it again, or to be suspicious of it.

Monolith, modular monolith or microservices?

And now the most expensive decision of all: how to deploy the application.

The monolith is a single application, with a single deploy and a single database. It's simple to develop, test and put live. The risk is that it turns into a "big ball of mud", where everything depends on everything.

The modular monolith is still a single deploy, but the code is divided into modules with clear boundaries, usually following DDD's bounded contexts. The modules talk through interfaces or events, and don't access each other's tables directly.

textapp/
├── Modules/
│   ├── Catalog/
│   │   ├── Actions/
│   │   ├── Models/
│   │   ├── Events/
│   │   └── Http/
│   ├── Billing/
│   └── Shipping/

Microservices take this to the extreme: each module becomes an independent application, with its own deploy and its own database, talking over the network (HTTP, queues, events).

And here's something that rarely comes up in talks: microservices trade code complexity for distributed complexity. Network calls fail. Transactions across services require patterns like the Saga. You start needing distributed observability, API versioning and coordinated deploys.

CriterionMonolithModular monolithMicroservices
Initial complexityLowMediumHigh
DeployOneOneMany
Team sizeSmallMediumMany independent teams
Scaling parts independentlyNoNoYes
Operational costLowLowHigh

The recommendation I most often see working in practice is: start with a well-modularised monolith. Extract a service only when there's a concrete reason, such as a part of the system with a load very different from the others, a team that needs full autonomy or a specific technological requirement. And a well-built modular monolith makes that extraction much easier when the time comes.

Event-driven architecture

There's one more style worth knowing. Instead of calling the next step directly, a component publishes an event, and other components react to it.

php// Synchronous and coupled
$order->save();
$this->mailer->sendReceipt($order);
$this->inventory->reserve($order);
$this->crm->notify($order);

// Event-driven
$order->save();
event(new OrderPlaced($order));   // the listeners react, often on a queue

Laravel makes this very natural, with events, queued listeners (ShouldQueue) and broadcasting. The gain is decoupling and resilience: if the CRM is down, the order is saved all the same, and the notification is processed again later. The price is eventual consistency (things don't all happen at the same instant) and a flow that's harder to follow.

One event, several listeners on the queueOrder saved to OrderPlaced: dispatches. OrderPlaced to Queue: queues. Queue to SendReceipt. Queue to ReserveStock. Queue to NotifyCrm. Scenario CRM down: One listener fails, the order doesn't. The order is already saved and the receipt and stock carry on as normal. The CRM job fails and goes back on the queue, to try again later. Queue to NotifyCrm failing. NotifyCrm down. Hint: php artisan queue:retry.Order savedin the databaseOrderPlacedeventQueueShouldQueueSendReceiptlistenerReserveStocklistenerNotifyCrmlistenerdispatchesqueuesNotifyCrmlistener
One event, several listeners on the queueOrder saved to OrderPlaced: dispatches. OrderPlaced to Queue: queues. Queue to SendReceipt. Queue to ReserveStock. Queue to NotifyCrm. Scenario CRM down: One listener fails, the order doesn't. The order is already saved and the receipt and stock carry on as normal. The CRM job fails and goes back on the queue, to try again later. Queue to NotifyCrm failing. NotifyCrm down. Hint: php artisan queue:retry.Order savedin the databaseOrderPlacedeventQueueShouldQueueSendReceiptlistenerReserveStocklistenerNotifyCrmlistenerdispatchesqueuesNotifyCrmlistener

CRM down

One listener fails, the order doesn't

The order is already saved and the receipt and stock carry on as normal. The CRM job fails and goes back on the queue, to try again later.

php artisan queue:retry

One event, several listeners on the queue

So where does Laravel stand?

This is the part I most wanted you to take from this episode. Laravel is opinionated at the edge and neutral at the centre:

  • It rigorously defines everything involving input and infrastructure: routing, middleware, validation, queues, cache, database.
  • It doesn't impose how to organise your business rules. The default structure, with app/Models and app/Http/Controllers, is a starting point, not a complete architecture.

In practice, a healthy evolution for Laravel projects usually goes like this:

  1. At the start: default structure, lean controllers, Form Requests and Policies.
  2. Growing: extract Actions or Services for the use cases, use DTOs to carry data between layers, create value objects for the important concepts and use events for side effects.
  3. Complex domain: organise the code by modules or contexts, instead of by technical type, and define interfaces for external integrations.
  4. Organisational scale: only then think about extracting services.

Notice that each step only happens when the pain justifies it. Good architecture is the kind that keeps pace with the size of the problem.

Record your decisions: ADRs

One last tip, one I wish I'd been given earlier. Architecture decisions get lost over time. Two years from now, someone will ask "why do we use Redis for sessions?", and nobody will remember.

An ADR (Architecture Decision Record) is a short document that records the context, the decision and the consequences:

markdown# ADR 007: Use queues to send notifications

## Context
Sending emails synchronously added up to 3 seconds to checkout.

## Decision
Notifications will be sent by listeners queued on Redis, processed by Horizon.

## Consequences
- Faster checkout, resilient to email provider failures.
- We need to monitor the queue and handle jobs that fail.

It takes ten minutes to write and saves hours of discussion in the future.

What to take into the saga

  • Architecture is the set of decisions that are expensive to reverse.
  • MVC separates presentation and data, but isn't enough for large applications.
  • Layers, hexagonal and Clean Architecture isolate business rules from infrastructure using dependency inversion.
  • DDD is, above all, about the language and boundaries of the business.
  • Start with a modular monolith; microservices answer organisational and scaling problems.
  • Laravel is strict at the edge and flexible at the centre: the architecture of the domain is your responsibility.

Next episode

Everything we've seen so far has decades of maturity. But in recent years, a new component has appeared in applications, and it has a characteristic no other one had: it isn't deterministic. I'm talking about language models.

What patterns were born from that? Do the classics still apply? And what changes for those who write software with the help of AI? In the next episode, we'll talk about software engineering in the age of AI, without hype and without panic. See you in episode 10.

References and further reading

Books

  • Software Engineering: A Practitioner's Approach, by Roger S. Pressman and Bruce R. Maxim (McGraw-Hill). The work that has accompanied this article since the first page.
  • Fundamentals of Software Architecture, by Mark Richards and Neal Ford (O'Reilly). Architectural styles and their trade-offs.
  • Clean Architecture, by Robert C. Martin (Prentice Hall).
  • Domain-Driven Design: Tackling Complexity in the Heart of Software, by Eric Evans (Addison-Wesley).

Online reading