Strong Like Bull
Strong Like Bull

Reputation: 11297

How do I access user manager as a service using FosUserBundle in Symfony?

So normally I can access the User Manager in a controller by doing something like:

$this->get('fos_user.user_manager');

However I have need to access this in a service. So this is what i did:

In my config.yml file:

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: Main\UserBundle\Entity\User



services:
    userbundle_service:
        class:        Main\UserBundle\Controller\UserBundleService
        arguments: [@fos_user]

In my UserBundleService.php":

<?php
namespace Main\UserBundle\Controller;

use FOS\UserBundle\Entity\User;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Bridge\Monolog\Logger;



class UserBundleService
{

     protected $securityContext;

    public function __construct(User $user)
    {
        $this->user = $user;
    }


    public function validateRequest(){    
   $userManager = $this->container->get('fos_user.user_manager');
  $this ->logger->warn("user is : ".$userManager);
  exit;

    }

}

The error I get is:

ServiceNotFoundException: The service "userbundle_service" has a dependency on a non-existent service "fos_user".

So the next thing I do is I move the fos_user in as a service in my config.yml :

services:
    userbundle_service:
        class:        Main\UserBundle\Controller\UserBundleService
        arguments: [@fos_user2]

    fos_user2:
        user_class: Main\UserBundle\Entity\User

I get the error:

RuntimeException: The definition for "fos_user2" has no class. If you intend to inject this service dynamically at runtime, please mark it as synthetic=true. If this is an abstract definition solely used by child definitions, please add abstract=true, otherwise specify a class to get rid of this error.

Upvotes: 2

Views: 12402

Answers (1)

Vitalii Zurian
Vitalii Zurian

Reputation: 17976

You have to inject service exactly with same name as you usually get it in your controller using service container:

services:
    userbundle_service:
        class:        Main\UserBundle\Controller\UserBundleService
        arguments: [@fos_user.user_manager]

You also can call in console app/console container:debug and check which containers you have

Upvotes: 5

Related Questions