2017-09-04 8 views
2

私はCommonと呼ばれる作成したカスタムクラスからMonologライブラリの情報をログに記録しようとしています。Symfony - カスタムクラスからのサービスへのアクセス

することは私には私もそのクラスのロガーインタフェースを初期化した

parameters: 
services: 
    appbundle.helper.common: 
    class: AppBundle\Helpers\Common 
    arguments: ['@doctrine','@logger'] 

そのクラスのservice.ymlで引数としてロガーが含まれています。

private $dataEntityManager; 
    private $suppEntityManager; 
    private $curation; 
    private $innerDoctrine; 
    private $logger; 

    /** 
    * Common constructor. 
    * @param ManagerRegistry $doctrine 
    */ 
    public function __construct(ManagerRegistry $doctrine, LoggerInterface $logger) 
    { 
     $this->dataEntityManager = $doctrine->getManager(); 
     $this->suppEntityManager = $doctrine->getManager('gtsupp'); 
     $this->curation = new Curation($doctrine); 
     $this->innerDoctrine = $doctrine; 
     $this->logger = $logger; 
    } 
    public function detail($a, $b, $c, $d, $e, $f = "", $g = true, $h = true) 
    { 

     $this->logger->error('Type not supplied in Common detail ' . __LINE__ . " for descriptor: " . $b); 

    } 

問題は、私はクラス::共通を使用するたびに、私はクラスのコンストラクタでロガーを提供しなければならないということです。

class DefaultController extends Controller 
    { 
     /** 
     * @Route("/", name="homepage") 
     */ 
     public function indexAction(Request $request) 
     { 
      $common = new Common($this->getDoctrine(), $this->get('logger')); 
      $common->detail('a', 'b', 'c', 'd', 'e'); 

      return $this->render('default/index.html.twig', [ 
       'base_dir' => realpath($this->getParameter('kernel.root_dir') . '/..') . DIRECTORY_SEPARATOR, 
      ]); 
     } 
    } 

P.S. doctrineで同じ問題が発生します。上記のようにCommonクラスを呼び出すたびに渡す必要があります。

+0

s未満の答えとしてコンテナからそれを引っ張りますuggestsは伝統的な方法です。あなたがS3.3 +を使用している場合は、public function indexAction(Request $ request、Common $ common)を試してください – Cerad

答えて

1

変更この:これに

$common = new Common($this->getDoctrine(), $this->get('logger')); 

:あなたはあなたをインスタンス化するためにすべてのパラメータを渡す必要はありません良い方法では、依存性注入を使用していない、あなたのように

$common = this->get('appbundle.helper.common'); 

サービス

https://symfony.com/doc/current/components/dependency_injection.html

+0

ありがとうございました。これと一緒にドキュメントを私に提供してもらえますか?私は決してそれを見つけなかった。 – marioskamperis

+1

https://symfony.com/doc/current/components/dependency_injection.html @marioskamperisよろしくお願いします。 –

関連する問題