2017-09-04 92 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乐于帮助你! –