如何从UserProvider类访问EntityManager

时间:2011-10-27 10:42:24

标签: doctrine symfony

我想从 UserProviderClass 访问 EntityManager ,以便能够在用户通过API登录后立即将用户保留在我的数据库中。

但是这个类实现了 UserProviderInterface ,并且没有扩展控制器,所以这段代码无法工作:

$em = $this->getDoctrine()->getEntityManager();

这是完整的课程

<?php
namespace am\ContributionBundle\Objects;

use am\ContributionBundle\Entity\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

class UserProvider implements UserProviderInterface
{
    public function loadUserByUsername($username){

            // Processing to the authentification using curl

            $url = 'exemple.com/api.php?pseudo='.$username;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            $output = json_decode(curl_exec($ch));
            curl_close($ch);

            try {

                $user = // ... looking for user in DB
                // How to ??

                if (null === $user) {
                    // ... user creation
                }

                return $user;

            } catch (\Exception $e) {
                echo $e->getMessage();
                throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username));
            }
    }

    function supportsClass($class){}

    function refreshUser(UserInterface $user){
       return $this->loadUserByUsername($user->getUsername());
    }
}

如何在此处获取EntityManager的实例?

1 个答案:

答案 0 :(得分:1)

尝试扩展Symfony \ Component \ DependencyInjection \ ContainerAware。然后,您可以使用容器查找任何对象。

另请记住将其配置为服务:http://symfony.com/doc/current/book/service_container.html