1

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.

1
  • Can you be more clear with letting us know what isn't working and what exactly are you expecting. Commented Aug 27, 2017 at 15:38

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

5 Comments

Can you extend your answer by an example?
Why do you have two getImapClient()?
Just an error with pasting the code... the second one should be "get()" and in the "getImapClient()" return $this->instance->get(). I modify the answer
Why you can not return $this->imapClient directly in getImapClient()?
You can... Using a getter is not required

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.