POV
POV

Reputation: 12025

How to use Dependency Injection in class?

I have custom class with DI ImapClient $imapClient:

class MailBoxCleaner
{
  public function __construct(ImapClient $imapClient)
  {
  }
}

And there is an facade class:

class ImapConnection {

  public function __construct()
  {
     return new ImapClient();
  }
}

I tried to use this like:

$MailBoxCleaner = new MailBoxCleaner(new ImapConnection());

But it does not work.

Upvotes: 1

Views: 42

Answers (1)

Jean-Luc Aubert
Jean-Luc Aubert

Reputation: 620

A constructor never return any data.

You have to create a getter method that return the instance of your ImapClient class, so you inject it in the other class.

Based on your code :

class ImapConnection {
  private $imapClient = null;

  public function __construct()
  {
     $this->imapClient = new ImapClient();
  }

  public function getImapClient(){
    return $this->imapClient;
  }
}

You can inject :

$idObj = new ImapConnection(); // Instanciation

$MailBoxCleaner = new MailBoxCleaner($idObj->get());

You also can use a "pattern" :

class ImapConnection {
  private $instance = null;
  private $imapClient = null;

  private function __construct()
  {
     $this->imapClient = new ImapClient();
  }

  public static function getImapClient(){
    if(is_null($this->instance){
        $this->instance = new ImapConnection();
    }
    return $this->instance->get();
  }


  private function get(){
    return $this->imapClient;
  }
}

Then, you can use in your code :

$MailBoxCleaner = new MailBoxCleaner(ImapConnection::getImapClient());

Upvotes: 1

Related Questions