gpt4 book ai didi

Symfony2 : How to pass a URL to a service (without passing entire router service)

转载 作者:行者123 更新时间:2023-12-02 04:32:15 24 4
gpt4 key购买 nike

我有一个用常规 PHP 编写的类/库(为了解释起见,我们称其为“foobar”类)。我正在为此编写一个 Symfony2 Bundle,以使 foobar 成为 Symfony2 服务并允许通过 config.yml 配置该类。

foobar 类需要一个关联数组传递给构造函数,其中数组元素之一是 URL。我想要传递的这个 URL 来自 Symfony 路由器。我无法注入(inject)整个路由器,我只想传递 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 目前是硬编码的,但希望从路由器中确定它(使用此 bundle 也定义的命名路由)。我该如何做到这一点或者是否有好的替代技术?

请注意,我是用 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

关于Symfony2 : How to pass a URL to a service (without passing entire router service),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22765693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com