开发者

Dependency Inversion Principle in PHP

开发者 https://www.devze.com 2023-02-15 18:54 出处:网络
Since PHP is a loosely typed language,开发者_如何学JAVA how can the DIP principle be applied in PHP?

Since PHP is a loosely typed language,开发者_如何学JAVA 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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号