0

我需要根据用户名或电子邮件地址在 symfony2 中找到一个用户对象。这不是用于登录,而是用于用户的其他操作。

我可以简单地请求(Doctrine2)存储库并从我的存储库类上的 UserProviderInterface 调用 loadByUsername 方法。

但是需要这样做的代码将在多个项目中使用,我需要它更通用一点。用户类/表可能不同,或者用户可能来自完全不同类型的提供者。

有没有办法像 Symfony2 本身在登录时使用的那样通过用户名查找用户?这样,无论用户提供者如何在 security.yml 中配置,它都可以工作。

Symfony2 中是否有一些我可以使用的服务?是否有“用户提供者服务”,我可以在其中调用类似“loadUserByUsername”之类的方法来尝试每个配置的提供者?

4

2 回答 2

1

After some poking into the SecurityBundle of Symfony itself, I figured out the following:

Given this is in your security.yml:

providers:
    AdministrationUser:
        entity:
            class: AdministrationBundle\Entity\User

Symfony will create a service with the following name:

security.user.provider.concrete.administrationuser

This service uses the UserProviderInterface and when you fetch this service you can simply call the method loadUserByName and find your user.

So all you need to know is the name of the provider you configured yourself and you can determine the service-name and fetch it.


I'm in a more generic situation, so I added an alias to that service in the Extension-class of my bundle:

    // alias the user_provider mentioned
    $container->setAlias('my_security_bundle.user.provider', new Alias('security.user.provider.concrete.' . strtolower($config['user']['provider'])));

Where $config['user']['provider'] comes from config.yml (and needs to be configured in your Configuration class, but that is a different story.

Now I can simply use that new alias and I will get the correct service to find my user in a Controller like so:

    /** @var UserProviderInterface $userProvider */
    $userProvider = $this->get('my_security_bundle.user.provider');
    $user = $userProvider->loadUserByUsername('someone@somewhere.tld');
于 2015-04-26T07:47:00.310 回答
0

如果我理解你的问题。

看到它http://symfony.com/doc/current/cookbook/security/multiple_user_providers.html

于 2015-04-23T12:51:41.593 回答