Skip to content
Home SE
Software

Dependency Inversion Principle

Sinan Eldem

• 6 min read

Dependency Inversion Principle

In this article we will cover the fifth and final SOLID principle. Wondering “What were these principles again?” Go ahead and read the summary article.

We have reached our final destination in our review of the five SOLID design principles! This final principle is the Dependency Inversion principle, and it states that high-level code should not depend on low-level code. Instead, high-level code should depend on an abstraction layer that serves as a "middle-man" between the high- and low-level code. A second aspect of the principle is that abstractions should not depend upon details, but rather details should depend upon abstractions. If this all sounds extremely confusing, don't worry. We'll cover both aspects of this principle below.

Dependency Inversion Principle

This principle states that high-level code should not depend on low-level code, and that abstractions should not depend upon details.

To illustrate this principle, let's consider the following class:

class Authenticator {

    public function __construct(DatabaseConnection $db)
    {
        $this->db = $db;
    }

    public function findUser($id)
    {
        return $this->db->exec('select * from users where id = ?', [$id]);
    }

    public function authenticate($credentials)
    {
        // Kullanıcı kimliğini doğrula...
    }

}

As you might have guessed, the Authenticator class is responsible for finding and authenticating users. Let's examine the constructor of this class. You will see that we are type-hinting a DatabaseConnection instance. So we're tightly coupling our authenticator to the database, essentially saying that users will always be provided out of a relational SQL database. Furthermore, our high-level code (the Authenticator) is directly relying on low-level code (the Database\Connection).

First, let's discuss "high-level" and "low-level" code. Low-level code implements basic operations like reading files from a disk or interacting with a database. High-level code encapsulates complex logic and relies on the low-level code to function, but should not be directly coupled to it. Instead, the high-level code should depend on an abstraction that sits on top of the low-level code, such as an interface. Not only that, but the low-level code also depends on an abstraction. So, let's write an interface that we can use within our Authenticator:

interface UserProviderInterface {
    public function find($id);
    public function findByUsername($username);
}

Next let's inject an implementation of this interface into our Authenticator:

class Authenticator {

    public function __construct(UserProviderInterface $users,
                                HasherInterface $hash)
    {
        $this->hash = $hash;
        $this->users = $users;
    }

    public function findUser($id)
    {
        return $this->users->find($id);
    }

    public function authenticate($credentials)
    {
        $user = $this->users->findByUsername($credentials['username']);

        return $this->hash->make($credentials['password']) == $user->password;
    }

}

After making these changes, our Authenticator now relies on two high-level abstractions: UserProviderInterface and HasherInterface. We are free to inject any implementation of these interfaces into the Authenticator. For example, if our users are now stored in Redis, we can write a RedisUserProvider which implements the UserProvider contract. The Authenticator is no longer depending directly on low-level storage operations.

Furthermore, our low-level code now depends on the high-level UserProviderInterface abstraction, since it implements the interface itself:

class RedisUserProvider implements UserProviderInterface {

    public function __construct(RedisConnection $redis)
    {
        $this->redis = $redis;
    }

    public function find($id)
    {
        $this->redis->get('users:'.$id);
    }

    public function findByUsername($username)
    {
        $id = $this->redis->get('user:id:'.$username);

        return $this->find($id);
    }

}

Inverted Thinking

Applying this principle inverts the way many developers design applications. Instead of coupling high-level code directly to low-level code in a "top-down" fashion, this principle states that both high- and low-level code depend upon a high-level abstraction.

Before we "inverted" the dependencies of our Authenticator, it could not be used with anything other than a database storage system. If we changed storage systems, our Authenticator would also have to be modified, in violation of the Open Closed principle. Again, as we have seen before, multiple principles usually stand or fall together.

After forcing the Authenticator to depend upon an abstraction over the storage layer, we can use it with any storage system that implements our UserProviderInterface contract without any modifications to the Authenticator itself. The conventional dependency chain has been inverted and our code is much more flexible and welcoming of change!

Sinan Eldem

Custom software and AI solutions with Laravel

Related posts

Software
6 min read

Laravel Eloquent Relationships Quick Reference Guide

This quick reference is a practical guide that explains the most common relationship types with simple examples. Covering hasOne, hasMany, belongsTo, belongsToMany and polymorphic relationships along with eager loading and performance tips, it gives developers a fast and accurate reference.

Read more