2017-01-22 7 views
0

はこれまでのところ、私はサービス依存性注入Approachh Symfony2の

を注入する2つの方法を考え出した

方法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; 

} 

私は以下のようなサービスを使用します

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

方法B:

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

そしてAは、より具体的に見えますが、サービスBがサービスA [サイクル]

誰かが違いを説明できますか?含まれている場合Serivce AがサービスBを含めるカントとして、それは依存を制限

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

下記の方法としてそれを使用しますか

答えて

2

違いは、最初のパターンがDependency Injectionと呼ばれることである(あなたの場合には、具体的にコンストラクタインジェクション)、他のパターンは正反対、すなわちService Locatorです。

Service Locatorパターンには多くの欠点があり、generally considered to be an anti-patternです。

+0

従属注入を使用して2つのサービスをお互いに使用する必要がある場合、どうすれば問題を解決できますか? –

+1

@ SelfSayedデザインを変更しました。巡回依存関係は設計上の匂いがあり、通常は単一責任原則違反に起因します。典型的な解決策は、古いクラスの両方が依存することができる新しいクラスにロジックの一部を抽出することです。 – Steven