1

How can I use UserPasswordEncoderInterface without having to declare it as a function parameter? I would like to use this method somewhere else and because of that I can't.

namespace App\Controller;
/.../
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserController extends AbstractController
{
     public function register(UserPasswordEncoderInterface $passwordEncoder, Request $request)
     {
     //some code here
     }
Kuba5822
  • 25
  • 6
  • Using the interface is easy, but what you want is the specifically implemented concrete version that Symfony gives you, right? Can you explain more why you are unable to use it elsewhere? Is it in a different class or a totally different project that doesn't use Symfony? – Chris Haas Jun 03 '21 at 21:30
  • I would like to use this method in different class. I would like to call this method without having to pass $passwordEncoder as a parameter. – Kuba5822 Jun 03 '21 at 21:34
  • I _think_, but don't know for sure, that you can use something like [this](https://stackoverflow.com/a/60079875/231316). You'll have to figure out the alias, or possibly manually tag it, however. That said, you are fighting an uphill battle and going against Symfony by doing so. You should be able to just pass that in the constructor and have everything work. If that's not an option for you code, build a very new simple class that acts as a middle-man in front of your class. – Chris Haas Jun 03 '21 at 21:41
  • Make a service if you want to re-use a part of your code, you won't have an argument problem too https://symfony.com/doc/current/service_container.html#fetching-and-using-services – HypeR Jun 04 '21 at 03:00

1 Answers1

1

If you use autowire: true in your config you can inject the service. docs

namespace App\Controller;

use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserController extends AbstractController
{
    private UserPasswordEncoderInterface $passwordEncoder;

    public function __construct(UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->passwordEncoder = $passwordEncoder;
    }

    public function register(Request $request)
    {
        // use it
        $this->passwordEncoder->encode();
    }
}
Vyctorya
  • 1,387
  • 1
  • 12
  • 18