Abstract repository and @Entity annotation inherit

2019-09-09 20:07发布

问题:

I implement a custom EntityRepository in a Symfony2 application.

I have an AbstractEntity (used as parent of some entities) :

/**
 * Abstract Entity.
 *
 * @ORM\Entity(repositoryClass="App\Util\Entity\AbstractRepository")
 */
abstract class AbstractEntity
{
    /**
     * Get id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    // ...
}

The custom EntityRepository :

/**
 * Abstract Repository.
 */
class AbstractRepository extends Doctrine\ORM\EntityRepository
{
    /**
     * Handles resource not found from find.
     *
     * @param int $id
     *
     * @return object
     */
    public function findOrFail($id)
    {
        if (null == $entity = $this->find($id)) {
            return $this->fail();
        }

        return $entity;
    }

   //...
}

And one of the entities that extends from AbstractEntity :

/**
 * @ORM\Table(name="tags_sport")
 */
class Tag extends AbstractEntity
{
     // ...
}

The custom repository is declared once in my AbstractEntity using @ORM\Entity annotation.
I want make my entities use the same repository without redeclare it.

But an error occurs :

Class "App\SportBundle\Entity\Tag" sub class of "App\Util\Entity\AbstractEntity" is not a valid entity or mapped super class

It's caused by the missing @ORM\Entity annotation in the child entity.

But nothing change.
If I add the @ORM\Entity annotation in the child entity, it will use the default EntityRepository.

How can I override the default EntityRepository for each entities extending from the AbstractEntity ?

EDIT I accept @Rvanlaak answer thanks to a gist given in the answer comments.
The final solution including the whole custom Repository in this gist

回答1:

These are two separate things, having an abstract parent entity, and having an abstract parent repository.

By default every entity will use the EntityRepository. The entity can have one repository, which can be defined via the ORM\Entity annotation: http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes

Let's say you create TagRepository yourself, there will be no problem with extending from your AbstractRepository.

Second, having an abstract entity. This is like telling Doctrine that your entity has a parent class. This isn't possible. The solution for that is to use traits. Found a nice article about that here: http://www.sitepoint.com/using-traits-doctrine-entities/