Pogledaj ovaj video:
Dependency Injection - Programming With Anthony
setMailer kao što kaže samo ime, postavlja. Cilj
DI je da nemaš
new operator unutar klase, već da "ubaciš" instance.
PHP kôd:
class NewsletterManager
{
protected $mailer;
public function __construct(\Mailer $mailer = NULL)
{
if ($mailer)
{
$this->mailer = $mailer;
}
}
public function setMailer(\Mailer $mailer)
{
$this->mailer = $mailer;
}
}
$mailer = new \Mailer;
$newsletterManager[0] = new NewsletterManager($mailer);
$newsletterManager[1] = (new NewsletterManager)->setMailer($mailer);
$newsletterManager[2] = new NewsletterManager(new \Mailer);
$newsletterManager[3] = (new NewsletterManager)->setMailer(new \Mailer);
Sve su ovo validni slučajevi, ali sve u zavisnosti od konteksta t.j. potrebe.