Reputation: 88187
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 ...
Upvotes: 20
Views: 13451
Reputation: 4582
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.
Upvotes: 4
Reputation: 44831
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
.
Upvotes: 38