如何使用Symfony中的FosUserBundle将用户管理器作为服务访问?

时间:2012-08-04 17:52:00

标签: php symfony fosuserbundle

通常我可以通过执行以下操作来访问控制器中的用户管理器:

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

但是我需要在服务中访问它。所以这就是我所做的:

在我的config.yml文件中:

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]

在我的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;

    }

}

我得到的错误是:

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

所以我接下来要做的是将fos_user作为服务移到config.yml中:

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

    fos_user2:
        user_class: Main\UserBundle\Entity\User

我收到错误:

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.

1 个答案:

答案 0 :(得分:5)

您必须使用与服务容器中通常使用相同名称的服务注入服务:

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

您也可以在控制台app/console container:debug中调用并检查您拥有的容器