2014-03-31 29 views
2

我有一個類/庫是用普通的PHP編寫的(爲了解釋的目的,我們稱之爲「foobar」類)。我正在爲此編寫一個Symfony2 Bundle,將foobar製作成Symfony2服務,並允許通過config.yml進行配置。Symfony2:如何傳遞一個URL到一個服務(不通過整個路由器服務)

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路由器作爲參數,因爲我希望其他開發人員能夠在其他框架中使用該庫。

+0

我看到你注入整個容器進入你的服務。什麼阻止你使用'$ container-> get('router')'來訪問路由器? – dmnptr

+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

相關問題