Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Respository from an Entity?

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

/**
 * @ORM\Entity(repositoryClass="...\GameRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Game {
    /**
     * @ORM\prePersist
     */
    public function setSlugValue() {
        $this->slug = $repo->createUniqueSlugForGame();
    }
}

In the prePersist method, I need to ensure that the Game's slug field is unique, which requires a database query. To do the query, I need access to the EntityManager. I can get the EntityManager from inside GameRepository. So: how do I get the GameRespository from a Game?

like image 450
Amy B Avatar asked Sep 17 '11 21:09

Amy B


3 Answers

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.

like image 186
Maurice Avatar answered Nov 20 '22 00:11

Maurice


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.

like image 27
Jani Hartikainen Avatar answered Nov 19 '22 23:11

Jani Hartikainen


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

like image 4
parisssss Avatar answered Nov 20 '22 00:11

parisssss