How to Get Current User inside Repository Symfony 2.7

Player1 picture Player1 · Jun 4, 2015 · Viewed 7.6k times · Source

All of my query in Entity Repository needs to be filtered by user.

Now I want to know how can I access the currently logged in user in Entity Repository directly.

What I did today is to get the currently logged in user in my controller, through the use of $this->getUser() and then pass it to Entity Repository and this is not efficient.

Answer

xurshid29 picture xurshid29 · Jun 4, 2015

You need to inject security.token_storage service into another one to get the current user, but as of Repository classes belong to Doctrine project, not Symfony, it is not recommended to do this.. May be there is a way to achieve it by creating custom entityManager class as described here, but I don't think it would a good solution..

Instead of customizing an entityManager better create a service which calls repository classes' methods, inject desired services into it.. Let Repository classes do their job.

Implementation would be something like this:

RepositoryClass:

class MyRepository extends EntityRepository
{
    public function fetchSomeDataByUser(UserInterface $user)
    {
        // query
    } 
}

Service:

class MyService
{
    private $tokenStorage;

    public function _construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
        // other services
    }

    public function getSomeDataByUser()
    {
        $user = $this->tokenStorage->getToken()->getUser();

        return $this->entityManager->getRepository(MyREPOSITORY)->fetchSomeDataByUser($user);
    }
}

Usage:

public function someAction()
{
    $dataByUser = $this->get(MYSERVICE)->getSomeDataByUser();
}