Reputation: 21449
Since PHP is a loosely typed language, how can the DIP principle be applied in PHP?
A practical example would be greatly appreciated.
Upvotes: 12
Views: 4416
Reputation: 4053
DIP is an guideline that:
A. High level modules should not should not depend upon low level modules. Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.
It is relevant regardless weather "modules" are actually classes, functions, modules (those do not exist in php per se), traits or anything else.
So Yes You can use DIP in PHP. In fact You can use it in PHP without ever writing classes! You can manage dependencies between functions the same way as You would for classes under DIP.
Upvotes: 0
Reputation: 4341
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()
{
// ...
}
}
Upvotes: 3