Symfony - 从自定义类访问服务

时间:2017-09-04 14:11:14

标签: symfony logging service doctrine monolog

我正在尝试使用我创建的名为Common的自定义类从Monolog库中记录信息。

我已将logger作为该类

的service.yml中的参数包含在内
parameters:
services:
   appbundle.helper.common:
   class: AppBundle\Helpers\Common
   arguments: ['@doctrine','@logger']

我还初始化了该类的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 :: Common 我必须在Class的构造函数中提供记录器

    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类时传递它,如上所示。

1 个答案:

答案 0 :(得分:1)

改变这个:

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

到此:

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

以你的方式你没有使用依赖注入,这样你就不需要传递所有参数来实例化你的服务

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