How to get a Respository from an Entity?

后端 未结 4 1356
遇见更好的自我
遇见更好的自我 2020-12-25 14:01

I have an Entity called Game with a related Repository called GameRepository:

/**
 * @ORM\\Entity(repositoryClass=\"...\\GameReposi         


        
相关标签:
4条回答
  • 2020-12-25 14:29

    You don't. Entities in Doctrine 2 are supposed to not know of the entity manager or the repository.

    A typical solution to the case you present would be to add a method to the repository (or a service class) which is used to create (or called to store) new instances, and also produces a unique slug value.

    0 讨论(0)
  • 2020-12-25 14:29

    You actually can get the repository in your entity and only during a lifecycle callback. You are very close to it, all you have to do is to receive the LifecycleEventArgs parameter.

    Also see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html

    use Doctrine\ORM\Event\LifecycleEventArgs;
    
    /**
     * @ORM\Entity(repositoryClass="...\GameRepository")
     * @ORM\HasLifecycleCallbacks()
     */
    class Game {
        /**
         * @ORM\prePersist
         */
        public function setSlugValue( LifecycleEventArgs $event ) {
            $entityManager = $event->getEntityManager();
            $repository    = $entityManager->getRepository( get_class($this) );
    
            $this->slug = $repository->createUniqueSlugForGame();
        }
    }
    

    PS. I know this is an old question, but I answered it to help any future googlers.

    0 讨论(0)
  • 2020-12-25 14:35

    you can inject the doctrine entity manager in your entity (using JMSDiExtraBundle) and have the repository like this:

    /**
     * @InjectParams({
     *     "em" = @Inject("doctrine.orm.entity_manager")
     * })
     */
        public function setInitialStatus(\Doctrine\ORM\EntityManager $em) {
    
    
        $obj = $em->getRepository('AcmeSampleBundle:User')->functionInRepository();
        //...
    }
    

    see this : http://jmsyst.com/bundles/JMSDiExtraBundle/1.1/annotations

    0 讨论(0)
  • In order to keep the logic encapsulated without having to change the way you save the entity, instead of the simple prePersist lifecycle event you will need to look at using the more powerful Doctrine events which can get access to more than just the entity itself.

    You should probably look at the DoctrineSluggableBundle or StofDoctrineExtensionsBundle bundles which might do just what you need.

    0 讨论(0)
提交回复
热议问题