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 ...
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:You don't need to register the fixture as a service. Make sure to import the used classes via
use
.For DoctrineFixturesBundle v. 3, you don't need to inject the container to inject a simple service. You can use normal dependency injection instead:
However if you do need the container, you can access it via the $this->container property.
Documentation here.