2012-06-11 24 views
1

我正在嘗試從數據庫加載用戶的Symfony2食譜教程。Symfony2 cookbook從數據庫教程加載用戶 - 存儲庫類丟失

本教程假定您有一個ACME/UserBundle,但我的安裝沒有,但我只是假設我可以自己創建(它不像我需要下載某個插件的插件)。

我創建了一個包UserBundle並從教程的實體User複製粘貼了代碼(第一個代碼框here)。

此行似乎打破東西對我來說:

@ORM\Entity(repositoryClass="Mycompany\UserBundle\Entity\UserRepository") 

該錯誤消息我得到的是:

Fatal error: Class 'mycompany\UserBundle\Entity\UserRepository' not 
found in /var/www/mycompany/vendor/doctrine/lib/Doctrine/ORM/EntityManager.php 
on line 578 

所以我不是以爲我不能只是創建自己的UserBundle(奇怪,因爲我認爲這是一個教程,如何做,而不是如何安裝一個插件),或者他們假設我知道我需要以某種方式在entityRepositories之間註冊實體?

如果在symfony中任何更高級的人都會在這方面給我啓發,我將不勝感激。到目前爲止,我真的很喜歡Symfony2的所有知識,但我在這裏學習速度很慢。

回答

1

這聽起來像你沒有一個用戶庫類,這是單獨的用戶實體類。它會在實體文件夾,但會UserRepository.php和看起來像:

namespace Mycompany\UserBundle\Entity; 

use Symfony\Component\Security\Core\User\UserInterface; 
use Symfony\Component\Security\Core\User\UserProviderInterface; 
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; 
use Symfony\Component\Security\Core\Exception\UnsupportedUserException; 
use Doctrine\ORM\EntityRepository; 
use Doctrine\ORM\NoResultException; 

// Implements userproviderinterface so we can use the user entity for authentication 
// Extends entityrepository so that it gets methods definded there 
class UserRepository extends EntityRepository implements UserProviderInterface { 

    // This function is called when a user tries to login, the below lets the user use their username or email for username 
    public function loadUserByUsername($username) { 
    $user = $this->createQueryBuilder('u') 
      ->select('u, r') 
      ->leftJoin('u.roles', 'r') 
      ->where('u.username = :username OR u.email = :username') 
      ->setParameter('username', $username) 
      ->getQuery(); 
    try { 
     $user = $user->getSingleResult(); 
    } catch (NoResultException $exc) { 
     throw new UsernameNotFoundException(sprintf('Unable to find an active UserBundle:User object identified by %s', $username)); 
    } 
    return $user; 
    } 
    // 
    public function refreshUser(UserInterface $user) { 
    $class = get_class($user); 
    if (!$this->supportsClass($class)) 
     throw new UnsupportedUserException(sprintf('instances of class %s are not supported', $class)); 
    return $this->loadUserByUsername($user->getUsername()); 
    } 

    public function supportsClass($class) { 
    return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName()); 
    } 

} 

這個類是可用futher下來,你在做http://symfony.com/doc/current/cookbook/security/entity_provider.html

+0

是真實的,但教程閱讀的方式,這個類似乎是可選的userBundle的工作,他們有一個用戶名或電子郵件登錄的方式,所以整個事情不應該打破沒有它... –

+0

這就是有些是真的,但是因爲你在實體類中用你在問題中提到的那一行聲明瞭存儲庫,所以你必須有一個。如果您不擴展用戶提供的界面,則不必像我的答案那樣預先填充它 – Luke

0

您應該能夠使用doctrine:generate:entities命令生成正確的類。 (Documented in the book.)

我覺得你的命令應該是這樣的:

php app/console doctrine:generate:entities User 
+0

啊哈教程,我以爲只是命令自動生成一些函數的實體,我不明白你需要運行它實際上創建實體類從你的代碼。 –