1

I want to use a data fixture to create users for testing purposes.

The problem is I need the FOS' user manager:

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

And for that I need the container. So how do I get it? It's not like when inside a controller, I can't do $this->get('fos_user.user_manager').

4

2 回答 2

3

The easiest solution is to extend 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('a@a.com');

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

If you are already extending another class, then you have to implement the ContainerAwareInterface, which takes just a few extra lines of code.

于 2012-08-26T17:21:04.270 回答
0

Unfortunately, this only works of you use the console. Loading fixtures via the API does not work well with container awareness and leads to errors, freezes and other issues.

于 2013-02-22T14:24:26.063 回答