我有一个用常规PHP编写的类/库(为了解释,我们称之为"foobar"类)。我正在为此编写一个 Symfony2 捆绑包,以使 foobar 成为 Symfony2 服务,并允许通过 config.yml 配置类。
foobar 类期望将关联数组传递给构造函数,其中一个数组元素是 URL。我想传递的这个URL派生自Symfony路由器。我无法注入整个路由器,我只想传递URL,我已经包含了我当前代码的示例,shuold 使其更容易解释。如果有人能为这种情况提出最佳做法,我们将不胜感激。
MySpecialBundle/Resources/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 LoaderXmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
}
在上面的这个文件中,您可以看到 URL 目前是硬编码的,但希望从路由器确定(使用此捆绑包也定义的命名路由)。我该怎么做,或者有没有好的替代技术?
请注意,我是用PHP编写的原始库的作者,但是我宁愿不修改它以接受Symfony2路由器作为参数,因为我希望其他开发人员能够在其他框架中使用该库。
您可以使用表达式语言。但它只是从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