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:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With