Symfony2:如何将URL传递给服务(不传递整个路由器服务)

时间:2014-03-31 15:27:40

标签: symfony dependency-injection

我有一个用常规PHP编写的类/库(为了解释,我们可以调用它" foobar"类)。我正在编写一个Symfony2 Bundle,以便将foobar变成Symfony2服务,并允许通过config.yml配置类。

foobar类需要一个传递给构造函数的关联数组,其中一个数组元素是一个URL。我想传递的URL来自Symfony路由器。我无法注入整个路由器,我只想传递URL,我已经包含了我当前代码的示例,这些代码很容易解释。如果有人能为这种情况提出最佳做法,我们将不胜感激。

MySpecialBundle /资源/ services.xml中

<?xml version="1.0" ?>
<container ......>
     <parameters>
          <parameter key="foobar.class">...</parameter>
     </parameters>
    <services>
    <service id="my_special_service" class="%foobar.class%">
            <argument type="collection">
                <argument key="url" >%my_special.url%</argument>
                <argument key="another_arg">%my_special.another_arg%</argument>
            </argument>
        </service>
    </services>
</container>

MySpecialBundle / DependencyInjection / MySpecialExtension.php

class MySpecialExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        //This is the URL that should be derived from the Symfony router
        $container->setParameter('my_special.url', 'http://this-url-should-come-from-router.com');
        $container->setParameter('my_special.another_arg', $config['another_arg']);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }
}

在上面的这个文件中,您可以看到URL目前是硬编码的,但希望从路由器确定(使用此捆绑包也定义的命名路由)。我怎么能这样做,还是有一个很好的替代技术?

请注意,我是用PHP编写的原始库的作者,但是我宁愿不修改它以接受Symfony2路由器作为参数,因为我希望其他开发人员能够在其他框架中使用该库。

1 个答案:

答案 0 :(得分:5)

您可以使用表达式语言。但它仅从Symfony 2.4引入。

因此,您的定义应该看起来更像或更像:

<container ......>
    <parameters>
        <parameter key="foobar.class">...</parameter>
    </parameters>
    <services>
        <service id="my_special_service" class="%foobar.class%">
            <argument type="expression">service('router').generate('some_path')</argument>
            <argument>%my_special.another_arg%</argument>
        </service>
    </services>
</container>

您可以在此处阅读有关表达语言的更多信息:

http://symfony.com/doc/current/book/service_container.html#using-the-expression-language

相关问题