我有一個類/庫是用普通的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路由器作爲參數,因爲我希望其他開發人員能夠在其他框架中使用該庫。
我看到你注入整個容器進入你的服務。什麼阻止你使用'$ container-> get('router')'來訪問路由器? – dmnptr
爲什麼你不能只注入路由器?問題是,如果你想注入一個生成的路由,在某些時候你必須使用路由器來生成它,而且這個邏輯必須在某個地方。 –