dshqd84261 2014-04-24 06:39
浏览 53
已采纳

如何在Symfony2中的Entity类中获取Kernel实例

The title explains the question pretty well. I am in the lifecycle callback of the Doctrine Entity class and want to do some extra DB entries. For this I need to get an instance of the Kernel. How can I do this?

  • 写回答

2条回答 默认 最新

  • dongyan5706 2014-04-24 07:33
    关注

    Needing the container/kernel in an entity is most of the time, wrong. An entity shouldn't be aware of any services. Why is that?

    Basically, an entity is an object which represents a thing. An entity is mostly used in a relationnal database, but you can at any time use this entity for other matters (serialize it, instanciate it from an HTTP layer...).
    You want your entity to be unit-testable, this means you need to be able to instanciate your entity easily, without anything around, mostly, without any piece of business logic.

    You should move your logic into another layer, the one that will instanciate your entity.
    For your use case, I think, the most easy way is to use a doctrine event.

    <kbd>services.yml</kbd>

    services:
        acme_foo.bar_listener:
            class: Acme\FooBundle\Bar\BarListener
            arguments:
                - @kernel
            tags:
                - { name: doctrine.event_listener, event: postLoad }
    

    <kbd>Acme\FooBundle\Bar\BarListener</kbd>

    use Symfony\Component\HttpKernel\KernelInterface;
    use Doctrine\ORM\Event\LifecycleEventArgs;
    use Acme\FooBundle\Entity\Bar;
    
    class BarListener
    {
        protected $kernel;
    
        /**
         * Constructor
         *
         * @param KernelInterface $kernel A kernel instance
         */
        public function __construct(KernelInterface $kernel)
        {
            $this->kernel = $kernel;
        }
    
        /**
         * On Post Load
         * This method will be trigerred once an entity gets loaded
         *
         * @param LifecycleEventArgs $args Doctrine event
         */
        public function postLoad(LifecycleEventArgs $args)
        {
            $entity = $args->getEntity();
    
            if (!($entity instanceof Bar)) {
                return;
            }
    
            $entity->setEnvironment($this->kernel->getEnvironment());
        }
    }
    

    And there you go, your entity remains flat without dependencies, and you can easily unit test your event listener

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误