Since PHP is a loosely typed language, how can the DIP principle be applied in PHP?
A practical example would be greatly appreciated.
The Dependency Inversion Principle (DIP) states that high level modules should not depend on low level modules; both should depend on abstractions. Abstractions should not depend on details.
The Dependency inversion principle is an important principle that helps us to decouple the importance things from the details. It protects us from a ripple effect from changes inside low level modules.
It turns out that a long time ago higher level modules depending on lower level modules was something that was considered good practice (before Object Oriented Design). The name “Dependency Inversion” is alluding to this.
Dependency Inversion Principle (DIP) : Principle used in architecting software. Inversion of Control (IoC) : Pattern used to invert flow, dependencies and interfaces. Dependency Injection (DI)
PHP 5 introduced "Type Hinting", which enables functions and methods to declare "typed" parameters (objects). For most cases, it should be not a big task to port examples, e.g. 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()
{
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With