0

So Far, I've figured out two ways to inject services

Method A:

public function __construct($entityManager, $mailer, $templating,$notificationManager,$taskManager,$leadNotificationManager,$dealNotificationManager,$taskNotificationManager) 
{
    $this->mailer = $mailer;
    $this->em = $entityManager;
    $this->templating = $templating;
    $this->notificationManager = $notificationManager;
    $this->taskManager= $taskManager;
    $this->leadNotificationManager = $leadNotificationManager;
    $this->dealNotificationManager = $dealNotificationManager;
    $this->taskNotificationManager = $notificationManager;

}

in that case I'll use the service as below

$this->mailer->send($message);  

Method B:

public function __construct(ContainerInterface $container) 
{
    $this->container = $container;
}

and use it as below

$this->container->get('crm_sandbox_google_calendar')->markDone($entity)

method A looks more specific, but it limits the dependancy as Serivce A cant Include service B if service B includes service A [cycle]

Can someone explain the difference?

Seif Sayed
  • 783
  • 2
  • 9
  • 18

1 Answers1

2

The difference is that the first pattern is called Dependency Injection (and in your case specifically Constructor Injection), while the other pattern is the exact opposite, namely Service Locator.

There are so many downsides to the Service Locator pattern, that it is generally considered to be an anti-pattern.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • So how do I fix the issue when two services need to use each other using dependancy injection ? – Seif Sayed Jan 22 '17 at 12:38
  • 1
    @SelfSayed you change the design. Cyclic dependencies aee a design smell and is usually caused by a Single Responsibility Principle violation. The typical solution is to extract part of the logic into a new class that both old classes can depend on. – Steven Jan 22 '17 at 13:52