2012-08-04 83 views
7

我試圖從夾具創建一個新的用戶管理員。我使用的是FOSUserBundle和Symfony2。使用datafixtures和fosuserbundle創建管理員用戶

$userManager = $this->container->get('fos_user.user_manager'); 

//$userAdmin = $userManager->createUser(); 

$userAdmin = new UserAdmin(); 
$userAdmin->setUsername('francis'); 
$userAdmin->setEmail('[email protected]'); 
$userAdmin->setEnabled(true); 
$userAdmin->setRoles(array('ROLE_ADMIN')); 

$userManager->updateUser($userAdmin, true); 

我總是收到此錯誤:

[ErrorException]           
Notice: Undefined property:  
INCES\ComedorBundle\DataFixtures\ORM\LoadUserAdminData::$container in 
/public_html/Symfony/src/INCES/ComedorBundle/DataFixtures/ORM/LoadUserAdminData.php line 16 
+0

爲什麼不使用fos:user:promote? – 2012-08-04 21:05:49

+0

我想在第一次在生產服務器上運行我的應用程序時創建一個管理員用戶。如果我知道促進作品改變已經創建的用戶的角色,但不完全是我想要的。 – 2012-08-05 22:18:08

回答

25

這爲我工作(我還使用FOSUserBundle):

// Change the namespace! 
namespace Acme\DemoBundle\DataFixtures\ORM; 

use Doctrine\Common\DataFixtures\FixtureInterface; 
use Doctrine\Common\Persistence\ObjectManager; 
use Symfony\Component\DependencyInjection\ContainerAwareInterface; 
use Symfony\Component\DependencyInjection\ContainerInterface; 

class LoadUserData implements FixtureInterface, ContainerAwareInterface 
{ 
    //.. $container declaration & setter 

    public function load(ObjectManager $manager) 
    { 
     // Get our userManager, you must implement `ContainerAwareInterface` 
     $userManager = $this->container->get('fos_user.user_manager'); 

     // Create our user and set details 
     $user = $userManager->createUser(); 
     $user->setUsername('username'); 
     $user->setEmail('[email protected]'); 
     $user->setPlainPassword('password'); 
     //$user->setPassword('3NCRYPT3D-V3R51ON'); 
     $user->setEnabled(true); 
     $user->setRoles(array('ROLE_ADMIN')); 

     // Update the user 
     $userManager->updateUser($user, true); 
    } 
} 

希望這可以幫助別人! :)

+0

爲我也酷了:) Tnx。 https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/user_manager.md - 這是userManager文檔,如果有人想做一些不同的事情:) – Petroff 2014-07-03 11:19:50

+0

它運作良好。感謝分享。 +1 – BentCoder 2014-09-23 08:24:07

3

按照文檔的this部分。

+0

最好的答案。謝謝。 – 2016-05-15 21:54:39

2

錯誤是因爲$容器當前未定義。要解決這個問題,請將ContainerAwareInterface添加到您的類定義中。

class LoadUserData implements FixtureInterface, ContainerAwareInterface 
{ 
    ... 
} 

這不會完全讓你得到你想要的東西,因爲你創建的用戶沒有UserManager。相反,你應該使用你已經註釋掉的線。

在我看來,你不需要UserAdmin類。管理員用戶應該是用戶的子集,只能通過他們擁有的角色進行區分。

您應該使用UserManager創建一個用戶(而不是UserAdmin)並設置角色。 如果您需要保留所有管理員用戶的索引,MySQL VIEW可以完成此操作,或者您可以創建自己的自定義「緩存」表並使用Doctrine Listeners在需要時更新它。

這個問題是相當古老的,所以我猜你找到了答案或至少一個解決方法。 你能提供嗎?回答你自己的問題是可以的。

相關問題