RDM LABSPORTUGUÊS

Technical article/ · 8 min read

Object orientation and SOLID in practice

Object orientation and SOLID in practice

Laravel Saga · Season 0 · Episode 06

If you learned object orientation at university or on a course, chances are you saw examples with dogs that inherit from animals and cars that have wheels. So did I. And the feeling afterwards is always the same: you open a framework's source code, find interfaces, contracts, traits and abstract classes everywhere, and can't connect one thing to the other.

In this episode, I want to build that bridge. We'll revisit the fundamentals of OO with examples from real web applications and then go through the SOLID principles. And I promise that, by the end, you'll understand why Laravel is organised the way it is.

The building blocks

Class, object and encapsulation

A class brings data and behaviour together. And encapsulation protects that data, so it can only change through valid paths. Look at this example:

phpfinal class Order
{
    private array $items = [];
    private OrderStatus $status = OrderStatus::Open;

    public function addItem(Product $product, int $quantity): void
    {
        if ($this->status !== OrderStatus::Open) {
            throw new DomainException('A closed order does not accept items.');
        }

        $this->items[] = new OrderItem($product, $quantity);
    }

    public function total(): Money
    {
        $cents = array_sum(array_map(fn (OrderItem $item) => $item->subtotal(), $this->items));

        return new Money($cents, 'BRL');
    }
}

Notice that nobody outside can do $order->items[] = ... and get around the closed-order rule. The rule lives next to the data it protects. It sounds simple, but it's the foundation of everything.

(The Money here is the value object from episode 04, which stores the amount in cents together with the currency.)

Interfaces: contracts

An interface defines what an object can do, without saying how it does it.

phpinterface PaymentGateway
{
    public function charge(Money $amount, string $token): PaymentResult;
}

final class StripeGateway implements PaymentGateway
{
    public function charge(Money $amount, string $token): PaymentResult
    {
        // calls the Stripe API
    }
}

final class PagarMeGateway implements PaymentGateway
{
    public function charge(Money $amount, string $token): PaymentResult
    {
        // calls the Pagar.me API
    }
}

Whoever uses a PaymentGateway doesn't know, and doesn't need to know, which company is processing the payment. And here's a piece of information that will help you a lot when navigating the framework: Laravel calls its interfaces contracts and keeps all of them in the Illuminate\Contracts namespace. There you'll find Cache\Repository, Queue\Queue, Mail\Mailer, Auth\Guard and many others.

Abstract classes

An abstract class is a class that is incomplete on purpose: it implements part of the behaviour and forces its children to complete the rest.

phpabstract class Report
{
    public function generate(): string
    {
        $data = $this->fetchData();

        return $this->format($data);
    }

    abstract protected function fetchData(): array;

    protected function format(array $data): string
    {
        return json_encode($data);
    }
}

You use classes like this in Laravel all the time, perhaps without noticing: Eloquent's Model, the FormRequest, Artisan's Command and the ServiceProvider are all bases you extend.

Inheritance or composition?

Inheritance (extends) expresses "is a". Composition (having another object as a property) expresses "has a" or "uses a".

Inheritance is tempting, I know. But it creates strong coupling: the child class depends on every detail of its parent, and deep hierarchies become fragile over time. That's why the classic advice is to prefer composition:

php// Problematic inheritance
class OrderService extends DatabaseConnection { /* ... */ }

// Composition
class OrderService
{
    public function __construct(
        private DatabaseConnection $db,
        private PaymentGateway $payments,
    ) {}
}

Makes sense, doesn't it? The OrderService isn't a database connection. It uses one.

Traits

Traits are reusable blocks of code that you "paste" into a class. They exist to work around PHP's lack of multiple inheritance.

phptrait HasSlug
{
    public function generateSlug(string $text): string
    {
        return strtolower(preg_replace('/[^a-z0-9]+/i', '-', trim($text)));
    }
}

class Post
{
    use HasSlug;
}

Laravel uses traits heavily: HasFactory, SoftDeletes, Notifiable and HasApiTokens on models; Dispatchable and Queueable on jobs. In your own code, though, take it easy. Too many traits hide where each method comes from, and you end up hunting for behaviour across five different files.

SOLID

Now on to SOLID, an acronym for five object-oriented design principles popularised by Robert C. Martin. Before we start, an honest warning: these principles aren't laws. They're heuristics, advice for writing code that copes with change. Use them with common sense.

PrincipleThe ideaWhere it shows up in Laravel
S · Single responsibilityOne reason to changeForm Request, Action, event and listener
O · Open/closedExtend without editingCache::extend(), Storage::extend()
L · Liskov substitutionAny implementation will doSwapping the queue driver in .env
I · Interface segregationSmall contractsShouldQueue, Responsable
D · Dependency inversionDepend on abstractionsIlluminate\Contracts

S — Single Responsibility Principle

A class should have one, and only one, reason to change.

Think about this controller:

php// Too many responsibilities
class UserController
{
    public function store(Request $request)
    {
        // validates the data
        // creates the user in the database
        // generates the avatar
        // sends the welcome email
        // records it in the CRM
        // builds the response
    }
}

If the email rule changes, you touch the controller. If the CRM changes, the same. If the validation changes, the same again. That's a lot of reasons to change the same place.

The good news is that Laravel gives you a place for each thing. The Form Request validates. An Action creates the user. A UserRegistered event triggers listeners that send the email and talk to the CRM. And the controller just coordinates all of it.

One reason to change in each piecePOST /users to StoreUserRequest: validates. StoreUserRequest to UserController: valid data. UserController to CreateUser: runs. CreateUser to UserRegistered: dispatches. UserRegistered to SendWelcomeEmail. UserRegistered to SyncToCrm.POST /usersthe requestStoreUserRequestForm RequestUserControllercoordinatesCreateUserActionUserRegisteredeventSendWelcomeEmaillistenerSyncToCrmlistenervalidatesvalid datarunsdispatches
One reason to change in each piece

The email changed? Touch the email listener. The CRM changed? The CRM listener. Each piece has its own reason.

O — Open/Closed Principle

Open for extension, closed for modification.

The idea is that you can add new behaviour without editing code that already works. Look at the difference:

php// Closed to extension: every new shipping method means editing this class
class ShippingCalculator
{
    public function calculate(Order $order, string $method): int
    {
        if ($method === 'correios') { /* ... */ }
        if ($method === 'jadlog') { /* ... */ }
        // a new method? one more if...
    }
}

// Open to extension
interface ShippingMethod
{
    public function calculate(Order $order): int;
}

class ShippingCalculator
{
    /** @param array<string, ShippingMethod> $methods */
    public function __construct(private array $methods) {}

    public function calculate(Order $order, string $method): int
    {
        return $this->methods[$method]->calculate($order);
    }
}

In the second version, a new shipping method is just a new class. The calculator doesn't change. And Laravel does exactly this with its drivers: you add a cache or filesystem driver with Cache::extend() or Storage::extend(), without touching a single line of the framework.

L — Liskov Substitution Principle

Objects of a subclass must be able to replace objects of the base class without breaking the program.

In plain words: if your code works with a PaymentGateway, it has to work with any implementation of it. Imagine an implementation that throws an exception in charge() because "this gateway only does refunds". It has the right signature, but it breaks the expectation of whoever uses the contract. That violates the principle.

It's thanks to this principle that Laravel can switch the queue driver from database to redis by changing a single environment variable, without anything in your code noticing.

I — Interface Segregation Principle

No client should be forced to depend on methods it does not use.
php// Fat interface
interface Storage
{
    public function read(string $path): string;
    public function write(string $path, string $contents): void;
    public function delete(string $path): void;
    public function temporaryUrl(string $path): string; // not every storage has this
}

// Segregated interfaces
interface Readable { public function read(string $path): string; }
interface Writable { public function write(string $path, string $contents): void; }

Laravel follows this principle by keeping its contracts small and focused. Some have no methods at all and serve only as a marker, like ShouldQueue: implementing it says "this class goes to the queue". Others have a single method, like Responsable, which only requires toResponse(). Each class implements only what makes sense for it.

D — Dependency Inversion Principle

High-level modules should not depend on low-level modules. Both should depend on abstractions.

I left the most important one for last, because it's the one that unlocks your understanding of Laravel. Look at this code:

phpclass CheckoutService
{
    public function finish(Order $order): void
    {
        $gateway = new StripeGateway('sk_live_...');   // depends on a concrete detail
        $mailer = new SmtpMailer('smtp.gmail.com');     // another concrete detail

        $gateway->charge($order->total(), $order->paymentToken);
        $mailer->send($order->customer->email, 'Order confirmed');
    }
}

Can you see the problems?

  • Swapping Stripe for Pagar.me means editing the CheckoutService.
  • Testing the checkout charges real cards and sends real emails.
  • The credentials are scattered across the code.

Now, inverting the dependency:

phpclass CheckoutService
{
    public function __construct(
        private PaymentGateway $gateway,
        private Mailer $mailer,
    ) {}

    public function finish(Order $order): void
    {
        $this->gateway->charge($order->total(), $order->paymentToken);
        $this->mailer->send($order->customer->email, 'Order confirmed');
    }
}

The CheckoutService, which is the business rule (high level), now depends on abstractions. And the concrete classes, which are the technical details (low level), depend on those abstractions too, because they implement them. The dependency arrow has been inverted. Before, it went from the CheckoutService straight to the StripeGateway. Now they all point to the contract:

After the inversion, everything points to the contractCheckoutService to PaymentGateway: depends on. StripeGateway to PaymentGateway: implements. PagarMeGateway to PaymentGateway: implements. FakeGateway to PaymentGateway: implements.CheckoutServicebusiness rulePaymentGatewayabstractionStripeGatewayproductionPagarMeGatewayalternativeFakeGatewaytestsdepends onimplementsimplementsimplements
After the inversion, everything points to the contractCheckoutService to PaymentGateway: depends on. StripeGateway to PaymentGateway: implements. PagarMeGateway to PaymentGateway: implements. FakeGateway to PaymentGateway: implements.CheckoutServicebusiness rulePaymentGatewayabstractionStripeGatewayproductionPagarMeGatewayalternativeFakeGatewaytestsdepends onimplementsimplementsimplements
After the inversion, everything points to the contract

In tests, you pass a FakeGateway. In production, a StripeGateway. And the CheckoutService doesn't change a comma.

The question that remains

Great: the CheckoutService now receives everything through its constructor. But hold on. Who creates the StripeGateway, with the right key, and hands it to the CheckoutService?

If it's the controller, the problem has only moved somewhere else. If it's several different classes, assembling objects spreads across the entire codebase.

php// Someone has to do this... somewhere
$service = new CheckoutService(
    new StripeGateway(config('services.stripe.secret')),
    new SmtpMailer(config('mail.host')),
);

Hold on to that question. It's the hook for the next episode.

What to take into the saga

  • Encapsulation keeps rules close to the data they protect.
  • Interfaces, which Laravel calls contracts, separate the "what" from the "how".
  • Prefer composition over inheritance and use traits sparingly.
  • SOLID explains how Laravel is organised: small responsibilities, extensible drivers and swappable contracts.
  • The Dependency Inversion Principle makes code depend on abstractions, and leaves an open question: who assembles the objects?

Next episode

The answer to that question has a name: Inversion of Control and Dependency Injection. In the next episode, we'll pull these concepts apart precisely (they're often confused) and then do something I think will surprise you: build a dependency injection container in PHP from scratch, autowiring and all. After that, Laravel's Service Container will never be a black box for you again. See you in episode 07.

References and further reading

Official documentation

Going deeper

Books

  • Agile Software Development: Principles, Patterns, and Practices, by Robert C. Martin (Pearson). The complete presentation of SOLID.
  • Refactoring, by Martin Fowler (Addison-Wesley). How to improve the design of existing code, step by step.