Sam*_*ony 2 dependency-injection symfony
我有一个用常规PHP编写的类/库(为了解释,我们称之为"foobar"类).我写一个Symfony2的套件,这使foobar的成Symfony2的服务,让全班同学通过config.yml进行配置.
foobar类需要一个传递给构造函数的关联数组,其中一个数组元素是一个URL.我想传递的URL来自Symfony路由器.我不能注入整个路由器,我只想传递URL,我已经包含了我当前代码的示例,其中shuold使其更容易解释.如果有人能为这种情况提出最佳做法,我们将不胜感激.
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>
Run Code Online (Sandbox Code Playgroud)
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');
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的这个文件中,您可以看到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>
Run Code Online (Sandbox Code Playgroud)
你可以在这里阅读更多关于表达语言
http://symfony.com/doc/current/book/service_container.html#using-the-expression-language
| 归档时间: |
|
| 查看次数: |
1325 次 |
| 最近记录: |