-1

I am looking for if it is possible to find the current user in a repository and if yes, how?

yivi
  • 42,438
  • 18
  • 116
  • 138
delph49
  • 79
  • 1
  • 11
  • 1
    do you mean ... injecting `Symfony\Component\Security\Core\Security` in the constructor and calling its `getUser` method? – Jakumi Sep 11 '19 at 09:09
  • 8
    Possible duplicate of [How do I get the entity that represents the current user in Symfony2?](https://stackoverflow.com/questions/7680917/how-do-i-get-the-entity-that-represents-the-current-user-in-symfony2) – Jeroen Sep 11 '19 at 09:09
  • @Jakumi that's the idea, I tried that, but it did not work – delph49 Sep 11 '19 at 09:12
  • @Jeroen this exemple is in a controller, I wan't do it in a repository – delph49 Sep 11 '19 at 09:13
  • "it did not work", care to elaborate with code and error message or something? because it is the correct approach, and it should definitely work – Jakumi Sep 11 '19 at 09:15
  • 1
    @delph49 The answers also show how to do it in a service, your repository is a service so you can apply those solutions. – Jeroen Sep 11 '19 at 09:17

1 Answers1

0

Inside your repository, edit your __construct, adding Security $security:

use Symfony\Component\Security\Core\Security;

/**
 * @var Security
 */
private $security;

public function __construct(RegistryInterface $registry, Security $security)
    {
        parent::__construct($registry, Entityname::class);
        $this->security = $security;
    }

then call getUser():

public function something(){
    $this->security->getUser()
}
Mateus
  • 56
  • 1
  • 9
  • Thanks to the response, but with this I have this error:Argument 1 passed to App\Core\Repository\HospitalisationRepository::__construct() must implement interface Symfony\Bridge\Doctrine\RegistryInterface, instance of Doctrine\ORM\EntityManager given, called in /home/docker/symfony/vendor/doctrine/doctrine-bundle/Repository/ContainerRepositoryFactory.php on line 84 – delph49 Sep 12 '19 at 06:30
  • That's weird. Can you post your code? And what is your Symfony version? – Mateus Sep 13 '19 at 11:40
  • 1
    it's ok, I did differently. Thanks – delph49 Sep 16 '19 at 10:50