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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php namespace WeCodePHP\HomeBundle\Entity; use Doctrine\ORM\EntityRepository; class UserRepository extends EntityRepository { public function findTotalMatches($keyword) { /* your awesome code block */ return 34; } } |
Now, in the original entity, we need to define which class should be used as the repository class. We do that like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php namespace WeCodePHP\HomeBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="WeCodePHP\HomeBundle\Entity\UserRepository") */ class User { } |
The repositoryClass tells Symfony2 about the custom repository.
Now, we can call our custom methods with ease:
1 2 3 |
<?php $userRepo = $this->getDoctrine()->getRepository('WeCodePHPHomeBundle:User'); var_dump($userRepo->findTotalMatches($keyword)); |
Custom repository is what we very often do in models in other frameworks.