【问题标题】:Symfony - Accessing Service from Custom ClassSymfony - 从自定义类访问服务
【发布时间】:2018-02-12 19:11:56
【问题描述】:

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

我在 service.yml 中包含了 logger 作为该类的参数

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,
            ]);
        }
    }

附: 教义也会出现同样的问题。正如你在上面看到的,每次我调用 Common 类时我都必须通过它。

【问题讨论】:

  • 按照下面的答案将其从容器中拉出是传统方式。如果您碰巧使用的是 S3.3+,请尝试 public function indexAction(Request $request, Common $common)

标签: symfony logging service doctrine monolog


【解决方案1】:

改变这个:

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

到这里:

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

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

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

【讨论】:

猜你喜欢
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
相关资源
最近更新 更多