• Service SHOULD NOT be possible to instantiate without passing all compulsory dependencies • Services SHOULD NOT instantiate others services, they always have to be injected (except Builders, Factories and Service Container) • Services SHOULD NOT have circular dependencies
method will be called public function setMailer(Mailer $mailer) { $this->mailer = $mailer; } public function notify($error) { $this->mailer—>send($error->to, $error->text); } }
Runtime is too late to know that dependency is not set if (!$this->mailer) { throw new \RuntimeException(‘Mailer is not injected :(’); } $this->mailer—>send($error->to, $error->text); } }
run unless you pass all dependencies public function __construct(Mailer $mailer) { $this->mailer = $mailer; } public function notify($error) { $this->mailer—>send($error->to, $error->text); } }
{ // You loosing control on how Mailer instantiated // Redundant dependancy on Swift Mailer $this->mailer = new Mailer($swiftMailer); } public function notify($error) { $this->mailer—>send($error->to, $error->text); } }
{ // Redundant dependancy on Mail Manager $this->mailer = $mailerManager->createMailer(); } public function notify($error) { $this->mailer—>send($error->to, $error->text); } }