tw332
tw332

Reputation: 47

Using custom entity repository with FOSUserBundle

I've added FOSUserBundle to my app and would like to use my own entity repository.

My app consists of several entities; Users, Jobs, Files and Comments. Since I've added FOSUserBundle, I've been able to re-map everything so the users/jobs/files/comments all link as they should but I've noticed in the profiler that the number of queries has increased.

For example - to show the user profile page, the db is now queried seperately to obtain user information, the jobs that relate that user and the comments that relate to those jobs. Previously one query would have obtained all that info using the query in my repository.

As the showAction controller is now provided by FOSUserBundle, my repository is not being used.

Is there any other way, apart from overriding the controllers (which seems like overkill for what I want to do) to call my own repository?

Edit: added entity code:

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity(repositoryClass="Test\TestBundle\Entity\Repository\TestUserRepository")
* @ORM\Table(name="users")
* @ORM\HasLifeCycleCallbacks
*/
class TestUser extends BaseUser
{
    // entity defintitions...
}

Repository code (which I used to call in my showAction method and would like to still use now):

use Doctrine\ORM\EntityRepository;

class TestUserRepository extends EntityRepository
{
    public function getUser($userId)
    {
        $qb = $this->createQueryBuilder('u')
                   ->select('u, j')
                   ->leftJoin('u.jobs', 'j')
                   ->leftJoin('u.files', 'f')
                   ->leftJoin('u.comments', 'c')
                   ->where('u.id = :userId')
                   //->addOrderBy('j.dateCreated', 'ASC')
                   ->setParameter('userId', $userId)
                   ;

        return $qb->getQuery()
                  ->getResult();
    }
}

Upvotes: 2

Views: 3066

Answers (1)

Thomas K
Thomas K

Reputation: 6216

Yes, you can define your custom repository in your entity.

/**
 * @ORM\Entity(repositoryClass="Foo\UserBundle\Entity\Repository\UserRepository")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
  ...
}

Upvotes: 2

Related Questions