Symfony 2.0 getting service inside entity

前端 未结 2 1230
难免孤独
难免孤独 2020-12-02 13:08

Im seraching over and cannot find answer. I have database role model in my application. User can have a role but this role must be stored into database.

But then us

2条回答
  •  渐次进展
    2020-12-02 14:07

    The reason why it's so difficult to get services into entities in the first place is that Symfony was explicitly designed with the intent that services should never be used inside entities. Therefore, the best practice answer is to redesign your application to not need to use services in entities.

    However, I have found there is a way to do it that does not involve messing with the global kernel.

    Doctrine entities have lifeCycle events which you can hook an event listener to, see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#lifecycle-events For the sake of the example, I'll use postLoad, which triggers soon after the Entity is created.

    EventListeners can be made as services which you inject other services into.

    Add to app/config/config.yml:

    services:
         example.listener:
               class: Alef\UserBundle\EventListener\ExampleListener
         arguments:
               - '@alef.role_service'
         tags:
               - { name: doctrine.event_listener, event: postLoad }
    

    Add to your Entity:

     use Alef\UserBundle\Service\RoleService;
    
     private $roleService;
    
     public function setRoleService(RoleService $roleService) {
          $this->roleService = $roleService;
     }
    

    And add the new EventListener:

    namespace Alef\UserBundle\EventListener;
    
    use Doctrine\ORM\Event\LifecycleEventArgs;
    use Alef\UserBundle\Service\RoleService;
    
    class ExampleListener
    {
         private $roleService;
    
         public function __construct(RoleService $roleService) {
             $this->roleService = $roleService;
         }
    
         public function postLoad(LifecycleEventArgs $args)
         {
             $entity = $args->getEntity();
             if(method_exists($entity, 'setRoleService')) {
                 $entity->setRoleService($this->roleService);
             }
         }
    }
    

    Just keep in mind this solution comes with the caveat that this is still the quick and dirty way, and really you should consider redesigning your application the proper way.

提交回复
热议问题