Symfony2 - 在编译器传递中注入文件系统

时间:2015-02-16 22:27:55

标签: php symfony

我需要根据配置数据创建服务。我得到了第一部分,我需要为此捆绑包设置CompilerPass并在容器中设置新定义。但是,我无法做的一件事就是从我的服务中的文件系统别名中注入一个gaufrette文件系统对象。

这是我的配置:

osc_storage:
    mappings:
        image:
            filesystem: image_storage_fs
            mimetypes:
                - 'image/jpeg'
                - 'image/png'
                - 'image/gif'
        video_file:
            filesystem: video_file_storage_fs
            mimetypes:
                - 'video/quicktime'
                - 'video/mp4'

这是我的compilerPass流程方法

public function process(ContainerBuilder $container)
    {
        $mappings = $container->getParameter('osc_storage.mappings');

        //we loop through all the mappings and create the uploader services
        foreach ($mappings as $name => $mapping) {

            $filesystem = $container->getAlias(
                $mapping['filesystem']
            );

            $definition = new Definition('OSC\StorageBundle\Uploader\FileUploader', array($filesystem, $mapping['mimetypes']));
            $container->setDefinition('osc_storage.uploader.' .$name, $definition);
        }


    }

这是FileUploader:

class FileUploader
{

    private $filesystem;

    private $mimetypes = array();

    public function __construct(Filesystem $filesystem, array $mimetypes)
    {
        $this->filesystem = $filesystem;
        $this->mimetypes = $mimetypes;
    }
}

但是,目前我收到以下错误:

RuntimeException in XmlDumper.php line 343:
Unable to dump a service container if a parameter is an object or a resource.
in XmlDumper.php line 343
at XmlDumper::phpToXml(object(Alias)) in XmlDumper.php line 292
at XmlDumper->convertParameters(array(object(Alias), array('image/jpeg', 'image/png', 'image/gif')), 'argument', object(DOMElement)) in XmlDumper.php line 170
at XmlDumper->addService(object(Definition), 'osc_storage.uploader.image', object(DOMElement)) in XmlDumper.php line 236
at XmlDumper->addServices(object(DOMElement)) in XmlDumper.php line 56
at XmlDumper->dump() in ContainerBuilderDebugDumpPass.php line 34
at ContainerBuilderDebugDumpPass->process(object(ContainerBuilder)) in Compiler.php line 117
at Compiler->compile(object(ContainerBuilder)) in ContainerBuilder.php line 614
at ContainerBuilder->compile() in bootstrap.php.cache line 2565
at Kernel->initializeContainer() in bootstrap.php.cache line 2344
at Kernel->boot() in bootstrap.php.cache line 2375
at Kernel->handle(object(Request)) in app_dev.php line 30

如果我手动创建服务,我只需要调用这样的服务:

osc_storage.thumbnail_uploader:
    class: OSC\StorageBundle\Uploader\FileUploader
    arguments: [@image_storage_fs]

基本上,我想在我的compilerPass类中做一个@image_storage_fs的方法!

1 个答案:

答案 0 :(得分:4)

你必须使用引用而不是对象本身:

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Definition;

new Definition('...', new Reference($mapping['filesystem']));