2012-08-26 56 views
1

我想使用data fixture來創建用戶用於測試目的。如何從數據夾具(或其他任何地方)獲取DIC?

的問題是我需要的FOS」用戶管理:

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

爲此,我需要的容器。那麼我怎麼得到它?這不像是在控制器內部,我不能做$this->get('fos_user.user_manager')

+3

您還沒有閱讀[documentation](http://symfony.com/doc/master/bundles/DoctrineFixturesBundle/index.html#using-the-container-in-the-fixtures)直到結束:) –

+0

@ m2mdas哈哈,你有我,謝謝 – ChocoDeveloper

回答

3

最容易的solution是擴展Symfony \ Component \ DependencyInjection \ ContainerAware。

<?php 

namespace SomeCompany\SomeBundle\DataFixtures\MongoDB; 

use Doctrine\Common\DataFixtures\FixtureInterface; 
use Doctrine\Common\Persistence\ObjectManager; 

use Symfony\Component\DependencyInjection\ContainerAware; 
use Symfony\Component\DependencyInjection\ContainerInterface; 

use SomeCompany\SomeBundle\Document\User; 

class LoadUsers extends ContainerAware implements FixtureInterface 
{ 
    /** 
    * {@inheritDoc} 
    */ 
    public function load(ObjectManager $manager) 
    { 
     $userManager = $this->container->get('fos_user.user_manager'); 
     $user = $userManager->createUser(); 

     $user->setUsername('myuser'); 
     $user->setEmail('[email protected]'); 

     $user->setPlainPassword('mypass'); 
     $user->addRole('ROLE_USER'); 
     $user->setEnabled(true); 
     $userManager->updateUser($user); 
    } 
} 

如果您已經在擴展另一個類,那麼您必須實現ContainerAwareInterface,它只需要額外的幾行代碼。

+0

請在你的答案中添加鏈接到文檔 –

+0

@thecatontheflat Sure =) – ChocoDeveloper

0

不幸的是,這隻適用於你使用控制檯。通過API加載裝置對於容器意識不佳,並導致錯誤,凍結和其他問題。

+0

你在說什麼?顯示一些代碼。據我所知,燈具是用來製作假數據的,或者像基本角色這樣的初始數據。爲什麼你需要一個API?只需運行命令。 – ChocoDeveloper

+0

如果您想將其包含在您的單元測試中,那麼您希望通過setUp()方法中的API調用它。至少這是理論。 我會顯示,但我已經扭轉了一切。如果你懷疑我,寫一個簡單的單元測試,同時使用燈具和容器意識。我試了半天,並沒有列出的20種方法在線工作,並導致phpunit凍結或進入無限循環。 – Tom

相關問題