如何将服务注入Symfony 2 Data Fixtures? [英] How to inject service into Symfony 2 Data Fixtures?

查看:48
本文介绍了如何将服务注入Symfony 2 Data Fixtures?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将服务注入 Symfony2 / Doctrine2数据夹具 ?我想创建虚拟用户,并需要 security.encoder_factory 服务来对我的密码进行编码。

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'

然后在我的数据夹具中

class LoadDataFixtures implements FixtureInterface {

    protected $passwordEncoder;

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

    public function load($em) {

但是得到了类似的东西


警告:
缺少参数1 ... \DataFixtures\ORM\LoadDataFixtures :: __construct(),在...中调用。

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


推荐答案

在灯具中使用容器部分确切说明了您的需求。

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

您需要做的就是在灯具中实现 ContainerAwareInterface 。这将导致Symfony通过Setter-Injection注入容器。示例实体看起来像这样:

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) {

不需要将灯具注册为服务。确保通过 use 导入使用的类。

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

这篇关于如何将服务注入Symfony 2 Data Fixtures?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆