Pogledajte određenu poruku
Staro 24. 03. 2013.   #2
webarto
expert
Grand Master
 
Avatar webarto
 
Datum učlanjenja: 11.04.2010
Poruke: 998
Hvala: 141
959 "Hvala" u 153 poruka
webarto is on a distinguished roadwebarto is on a distinguished roadwebarto is on a distinguished roadwebarto is on a distinguished roadwebarto is on a distinguished roadwebarto is on a distinguished roadwebarto is on a distinguished roadwebarto is on a distinguished road
Default

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.
__________________
Github // LinkedIn // PHP // ZCE // Stackoverflow PHP // Site5 Web Hosting
webarto je offline   Odgovorite uz citat
"Hvala" webarto za poruku: