Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject service into Symfony 2 Data Fixtures?

How can I inject a service into Symfony2/Doctrine2 Data Fixtures? I want to create dummy users and need the security.encoder_factory service to encode my passwords.

I tried defining my Data Fixture as a service

myapp.loadDataFixture:
    class: myapp\SomeBundle\DataFixtures\ORM\LoadDataFixtures
    arguments:
        - '@security.encoder_factory'

Then in my Data Fixture

class LoadDataFixtures implements FixtureInterface {

    protected $passwordEncoder;

    public function __construct($encoderFactory) {
        $this->passwordEncoder = $encoderFactory->getEncoder(new User());
    }

    public function load($em) {

But got something like

Warning: Missing argument 1 for ...\DataFixtures\ORM\LoadDataFixtures::__construct(), called in ...

like image 789
Jiew Meng Avatar asked Dec 30 '11 03:12

Jiew Meng


1 Answers

The Using the Container in the Fixtures section describes exactly what you need.

All you need to do is to implement the ContainerAwareInterface in your fixture. This will cause the Symfony to inject the container via Setter-Injection. An example entity would look like this:

class LoadDataFixtures implements FixtureInterface, ContainerAwareInterface {

     /**
     * @var ContainerInterface
     */
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load($em) {

You don't need to register the fixture as a service. Make sure to import the used classes via use.

like image 180
Elnur Abdurrakhimov Avatar answered Sep 21 '22 18:09

Elnur Abdurrakhimov