Since PHP is a loosely typed language, how can the DIP principle be applied in PHP?
A practical example would be greatly appreciated.
Since PHP is a loosely typed language, how can the DIP principle be applied in PHP?
A practical example would be greatly appreciated.
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()
{
// ...
}
}
DIP 是一个指导方针:
A. 高级模块不应依赖于低级模块。两者都应该依赖于抽象。
B. 抽象不应依赖于细节。细节应该取决于抽象。
无论天气“模块”实际上是类、函数、模块(这些在 php 本身中不存在)、特征或其他任何东西,它都是相关的。
所以是的,您可以在 PHP 中使用 DIP。事实上,您无需编写类就可以在 PHP 中使用它!您可以像管理 DIP 下的类一样管理函数之间的依赖关系。