How to inject service into Symfony 2 Data Fixtures

2020-05-25 06:35发布

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 ...

2条回答
Animai°情兽
2楼-- · 2020-05-25 06:38

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.

查看更多
Luminary・发光体
3楼-- · 2020-05-25 06:57

For DoctrineFixturesBundle v. 3, you don't need to inject the container to inject a simple service. You can use normal dependency injection instead:

// src/DataFixtures/AppFixtures.php
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

// ...
private $encoder;

public function __construct(UserPasswordEncoderInterface $encoder)
{
    $this->encoder = $encoder;
}

However if you do need the container, you can access it via the $this->container property.

Documentation here.

查看更多
登录 后发表回答