【发布时间】:2014-03-31 15:27:40
【问题描述】:
我有一个用普通 PHP 编写的类/库(为了便于解释,我们称之为“foobar”类)。我正在为此编写一个 Symfony2 Bundle,以使 foobar 成为 Symfony2 服务并允许通过 config.yml 配置该类。
foobar 类需要一个关联数组传递给构造函数,其中一个数组元素是 URL。我要传递的这个 URL 来自 Symfony 路由器。我不能注入整个路由器,我只想传递 URL,我已经包含了我当前代码的示例,它应该更容易解释。如果有人能针对这种情况提出最佳做法,我们将不胜感激。
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 Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
}
在上面的这个文件中,您可以看到 URL 目前是硬编码的,但希望由路由器确定(使用此捆绑包也定义的命名路由)。我该怎么做或者有没有好的替代技术?
请注意,我是用 PHP 编写的原始库的作者,但是我不想修改它以接受 Symfony2 路由器作为参数,因为我希望其他开发人员能够在其他框架中使用该库。
【问题讨论】:
-
我看到您将整个容器注入到您的服务中。是什么阻止您使用
$container->get('router')访问路由器? -
为什么不能只注入路由器?问题是,如果你想注入一个生成的路由,在某些时候你将不得不使用路由器来生成它,并且这个逻辑必须在某个地方。
标签: symfony dependency-injection