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 に答える