Categories
PHP

Symfony2 & Doctrine: Custom Entity Repositories

In Symfony2, we can easily map a custom repository class for an entity. This allows us to extend the functionality of the repository. For example, we can add custom methods for even more customizable data retrieval. Without any ado, let’s jump into codes.

First, create the class which will act as the repository. It must extend “Doctrine\ORM\EntityRepository”. Here, we’re creating a repository for “User” objects inside “WeCodePHP\HomeBundle\Entity”. You can get the entity manager using “$this->getEntityManager()” inside a method.

Now, in the original entity, we need to define which class should be used as the repository class. We do that like this:

The repositoryClass tells Symfony2 about the custom repository.

Now, we can call our custom methods with ease:

Custom repository is what we very often do in models in other frameworks.

One reply on “Symfony2 & Doctrine: Custom Entity Repositories”

Simple and straight forward, Just the pointer I needed when I was learning Symfony2 Entities.

 

Good work mate!

Comments are closed.