[英]Using EntityManager in a custom UserProvider
我試圖在Symfony2中的自定義用戶提供程序中使用“ Doctrines實體管理器”。
如您所見,我將其作為參數傳遞:
SnapsavedUserProvider:
class: Snap\ModelBundle\Security\SnapsavedUserProvider
arguments: ["@doctrine.orm.entity_manager"]
在課堂上,我會:
namespace Snap\ModelBundle\Security;
use Snap\RestBundle\Entity\User;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
class SnapsavedUserProvider implements UserProviderInterface {
protected $em;
public function __construct($em) {
$this->setEm($em);
/* IF i var dump $this-getEm() here, i get the EntityManager */
}
public function getEm() {
return $this->em;
}
public function setEm($em) {
$this->em = $em;
}
public function loadUserByUsername($username) {
var_dump($this->getEm());
/* But its NULL here? */
die();
$user = $this->getEm()
->getRepository('SnapRestBundle:User')
->findOneBy(array('username' => $username));
if ($user) {
return $user;
}
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
}
為什么我的EntityManager在loadUserByUsername方法中為NULL? 我的意思是,即使使用了新實例,也會注入並設置em,不是嗎?
在通過構造函數進行注入時,為什么要使用getter和setter? 另外,您缺少接口所需的幾種方法。
<?php
namespace Snap\ModelBundle\Security;
use Doctrine\ORM\EntityManager;
use Snap\RestBundle\Entity\User;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
class SnapsavedUserProvider implements UserProviderInterface
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function loadUserByUsername($username)
{
$user = $this->em
->getRepository('SnapRestBundle:User')
->findOneBy(array('username' => $username));
if ($user) {
return $user;
}
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
/**
* Refreshes the user for the account interface.
*
* It is up to the implementation to decide if the user data should be
* totally reloaded (e.g. from the database), or if the UserInterface
* object can just be merged into some internal array of users / identity
* map.
* @param UserInterface $user
*
* @return UserInterface
*
* @throws UnsupportedUserException if the account is not supported
*/
public function refreshUser(UserInterface $user)
{
// TODO: Implement refreshUser() method.
}
/**
* Whether this provider supports the given user class
*
* @param string $class
*
* @return Boolean
*/
public function supportsClass($class)
{
// TODO: Implement supportsClass() method.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.