2

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

$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.
4

1 回答 1

5

您必须注入与通常使用服务容器在控制器中获取它的名称完全相同的服务:

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

您还可以调用控制台app/console container:debug并检查您拥有哪些容器

于 2012-08-06T05:59:13.720 回答