Boosting Laravel Quality with SOLID Principles: Best Practices and Examples (Part V — D)

Niranjan Shrestha
2 min readApr 9, 2023

--

The Dependency Inversion Principle has a few characteristics that is pretty similar to Dependency Injection , but it’s not like that at all.

💡 Depend upon abstraction, not concretions.

Whenever you have a parent class and one or more sub-classes you should use the parent class as a dependency. For example:

Let’s say that our application has two types of users: Users and Administrators. Both are authenticable and have some message stuff between both. Now let’s apply the ISP to be more clear.

interface Authenticable {
public function auth(): bool;
}
interface Messenger {
public function prepareMessage(): string;

public function sendMessage(): bool;
}
class User implements Authenticable, Messenger 
{ /** */ }
class Administrator implements Authenticable, Messenger 
{ /** */ }
class ChatMessage {

public $model;

public function __construct(
Administrator $model,
string $message)
{
$this->model = $model;
}

public function handle() {
// handles messages stuff
}
}

If we stop to think, our High Level module on this example is the ChatMessage and it DEPENDS of a low level module, that is the Administrator class.

Following the 5th principle, it’s already wrong right? because both should be depending of an abstraction. So, ChatMessage we should inject Authenticable interface rather than Administrator class.

class ChatMessage {

public $model;

public function __construct (
Authenticable $model,
string $message
)
{
$this->model = $model;
}

public function handle() {
// handles messages stuff
}
}

Our dependency is now inverted. We don’t need to worry about make N classes to the same process, because everything is maintained in abstractions.

And that's it! We finished the SOLID principles.

Was this story of any value to you? Please support my work by leaving a 👏 clap as a token of appreciation.

Did you know that you can clap more than once? 🥰 Thank You.

--

--