Search code examples
doctrine-ormsymfony

How to get a Repository 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?


Solution

  • 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.