Reputation: 23038
I stumbled upon an interesting question about Doctrine's findAll() method.
The OP asked how could he call findAll()
with a limit
criteria, which is not natively supported by Doctrine2. The accepted answer wisely suggested him to look at the source code of this method and we learned from this that findAll()
does nothing more than calling findBy()
with particular arguments.
So calling findAll()
with a limit
of 13 can be done by calling directly:
findBy(array(), array('id' => 'DESC'), 13);
But when reading the code, this last instruction is not as straightforward as a call that would look like this:
findAllWithLimit(13);
My question is: where this method would belong if I wanted to make it application-wide?
public function findAllWithLimit($limit)
{
return $em->findBy(array(), array('id' => 'DESC', $limit);
}
Upvotes: 0
Views: 146
Reputation: 6256
First solution (less flexible/super easy)
You will need to override the default Repository class in your config.yml and make your own.
Let's make your own basic repository class:
namespace My\BaseBundle\Repository; // you will want to change
use Doctrine\ORM\EntityRepository as BaseEntityRepository;
class EntityRepository extends BaseEntityRepository
{
public function findAllWithLimit($limit) {
// your logic
}
}
Then in your config.yml file you would define the default entity repository of your entity manager.
doctrine:
orm:
entity_managers:
default: # you will have to figure out what the value is in your config.yml file
default_repository_class: My\BaseBundle\Repository\EntityRepository # make sure to put the proper namespace
For more Doctrine options in Symfony, check out the configuration reference here.
Second solution (most flexible/longest one)
You could create your own custom repository class and have it extend your own base repository class.
As an example, your own base repository class would be:
namespace My\BaseBundle\Repository;
use Doctrine\ORM\EntityRepository as BaseEntityRepository;
class EntityRepository extends BaseEntityRepository
{
public function findAllWithLimit($limit) {
// your logic
}
}
While each repository class would look like:
namespace My\AwesomeBundle\Repository;
use My\BaseBundle\Repository\EntityRepository;
class DogRepository extends EntityRepository
{
}
Then you define your Dog
entity so it points to the DogRepository
class. The documentation I gave you should teach you how to do it.
This solution requires more code but makes your code cleaner as it would allow to split your repository calls into methods.
Hope it helps!
Upvotes: 1