2017-09-04 84 views
2

我正在嘗試使用Monolog庫從自定義類中創建一個名爲Common的日誌信息。Symfony - 從自定義類訪問服務

我已經包括記錄器如service.yml該類

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

我還初始化記錄儀接口該類一個參數。

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. 同樣的問題與教條發生。每次我調用Common類時,都必須通過它,如上所示。

+0

將其從容器中拉出,作爲下面的答案s uggests是傳統的方式。如果你碰巧使用S3.3 +然後嘗試公共函數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樂於幫助你! –