Dependency Inversion Principle in PHP

Since PHP is a freely typed language, how can you apply the DIP principle in PHP?

Nice to appreciate a practical example.

+8
oop php solid-principles dip-principle
source share
2 answers

PHP 5 introduced "Type Hinting", which allows functions and methods to declare "typed" parameters (objects). In most cases, transferring examples, for example, should not be a big task. from Java to PHP 5.

A really simple example:

interface MyClient { public function doSomething(); public function doSomethingElse(); } class MyHighLevelObject { private $client; public __construct(MyClient $client) { $this->client = $client; } public function getStuffDone() { if ( any_self_state_check_or_whatever ) $client->doSomething(); else $client->doSomethingElse(); } // ... } class MyDIP implements MyClient { public function doSomething() { // ... } public function doSomethingElse() { // ... } } 
+3
source share

DIP is a guide that:

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

B. Abstractions should not depend on details. Details should depend on abstractions.

This is true if the "modules" of the weather are actually classes, functions, modules (those that do not exist in php as such), traits, or something else.

So you can use DIP in PHP. In fact, you can use it in PHP without writing classes! You can manage dependencies between functions in the same way as for classes under DIP.

0
source share

All Articles