0
votes

A simple but silly problem is blocking me on symfony tonight... I need to use the UserInterface class of the security component to retrieve information about the current user. However symfony tells me that this class doesn't exist. I checked "security" is well installed and the paths are good...

My code :

<?php

namespace App\Controller;

use App\Entity\Profile;
use App\Entity\Candidature;
use App\Form\CandidatureType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class CandidateController extends AbstractController
{
    /**
     * @Route("/candidate", name="candidate")
     */
    public function new(Request $request, UserInterface $user): Response
    {
        // NEED TO BE CONNECTED !!
        if ($user->getUsername()) {
            // SOME CODE ...........

        } else {
            return $this->redirectToRoute('security_login');
        }
    }
}

The error i get (screenshot)

Error i get (quote)

Cannot autowire argument $user of "App\Controller\CandidateController::new()": it references interface "Symfony\Component\Security\Core\User\UserInterface" but no such service exists. Did you create a class that implements this interface?

2
If you happen to be using Symfony 5.2+ then there a new PHP attribute called CurrentUser which will allow your code to work.Cerad

2 Answers

0
votes

The autowiring mechanisms only work for services and the UserInterface is not a service it’s just a contract to deal with the core security of Symfony. If you want to get the current user you should inject the Symfony\Component\Security\Core\Security class see documentation

-1
votes

In config/services.yml

services:
    App\Controller\CandidateController:
       arguments:
        $user: '@Symfony\Component\Security\Core\User'

-Add for $user the real class:

-You can also move this check to a service class itself, and inject this $user inside the service class.

EDIT:

Note this solution if you want to switch between different user components in the future and now.