Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Inversion Principle in PHP

Since PHP is a loosely typed language, how can the DIP principle be applied in PHP?

A practical example would be greatly appreciated.

like image 265
johnlemon Avatar asked Mar 10 '11 07:03

johnlemon


People also ask

What does dependency inversion principle mean?

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.

Why is the dependency inversion principle important?

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.

Why is it called Dependency Inversion?

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.

What is Dependency Inversion dip and IoC?

Dependency Inversion Principle (DIP) : Principle used in architecting software. Inversion of Control (IoC) : Pattern used to invert flow, dependencies and interfaces. Dependency Injection (DI)


1 Answers

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()
  {
    // ...
  }
}
like image 122
Flinsch Avatar answered Oct 12 '22 01:10

Flinsch