Symfony static/global 具有学说访问权限的记录器

Symfony static/global Logger with doctrine access

也许我尝试了不可能的事情,但我尝试归档一个日志系统,我可以在任何地方使用 Logger::info('some info') 或普通 LogInfo(...) 之类的东西进行日志记录。

所以没有使用 new .. 或 parameter/injection 进行预初始化(必须在某些具有“动态”参数计数的函数中使用它)。我需要在 controller/command 内部和外部使用较小的定制 类 和函数,由 controllers/commands 以某种方式调用但不扩展任何容器。

例如,我使用 Symfony 文档中的 MessageGenerator 示例

// srcMessageGenerator.php

namespace App\Library\Util;

use Doctrine\ORM\EntityManagerInterface;

class MessageGenerator
{
    private $em;
    public function setEM(EntityManagerInterface $em){
        $this->em = $em;
        var_dump('a');
    }

    public function getHappyMessage(){
        var_dump($this->em);
        $messages = [
            'You did it! You updated the system! Amazing!',
            'That was one of the coolest updates I\'ve seen all day!',
            'Great work! Keep going!',
        ];
    
        $index = array_rand($messages);
    
        return $messages[$index];
    }
}

我已经尝试将其定义为服务

# config/services.yaml
services:
    App\Library\Util\MessageGenerator:
        arguments: ['@doctrine.orm.entity_manager']
        public: true

问题: 我必须将它注入我想使用它的每个功能 - 不可能

我尝试将它用作静态函数 - 服务不能是静态的

我试图将它隔离为静态函数而不使用服务,但后来我不知道如何根据我的环境获得 config/package/doctrine 设置。

我也研究过 monolog,但这是同样的问题,如果不在 controller/command 之外声明,我无法使用它。

任何人都可以提示我如何访问默认的(基于 env 的)学说连接,或者我如何使用服务 inside/outside a controller/command 而不声明它(类似静态)并提供实体管理器。

(第二种方式的解决方案会很可爱,所以有一天我可以使用相同的解决方案“升级”到独白)

您可以通过将服务传递给控制器​​中的函数来在 Symfony 中使用 Injecting Services/Config into a Service

您的服务:

class MessageGeneratorService
{
    private $em;

    public function __construct(EntityManagerInterface $em){
        $this->em = $em;
    }
    public function getHappyMessage(){
    // the job
    }
}

在其他服务中:

class MyService
{
    private $messageGeneratorService;

    public __construct(MessageGeneratorService $mGService) {
        $this->messageGeneratorService = $mGService
    }

    // You can use this service like you use MessageGeneratorService
    public makeMeHappy() {
        $messageGeneratorService->getHappyMessage();
    }
}

在控制器中:

class MyController
{
    /**
     * @Route("/example", name="page_example")
     */
    public index(MessageGeneratorService $mGService) {
        $mGService->getHappyMessage(); // Now, you can use it
        return $this->render('example/index.html.twig');
    }
}

现在,您可以在控制器或服务中使用 MessageGeneratorService 实例:

The container will automatically know to pass the logger service when instantiating the MessageGenerator