【问题标题】:How do I pass a custom Router to a service in a Symfony Bundle?如何将自定义路由器传递给 Symfony Bundle 中的服务?
【发布时间】:2016-10-18 12:50:50
【问题描述】:

在我的 Bundle 中,我使用 FooBundle/Service/SessionHandler.php 下的 SessionHandler 服务

这得到了一个扩展 Symfony 路由器的定制路由器:

use FooBundle/Routing/Router
    (...)
    public function __construct(HttpUtils $httpUtils, array $options, Router $router) {
        $this->router = $router;
        $this->container = $router->getContainer();
        $this->defaultLogoutHandler = new DefaultLogoutSuccessHandler($httpUtils);
        parent::__construct($httpUtils, $options);
    }

这在 Symfony 2.1 中确实有效

在 3.1 中我得到一个例外:

可捕获的致命错误:传递给 FooBundle\Service\SessionHandler::__construct() 的参数 3 必须是 FooBundle\Routing\Router 的实例,给定 Symfony\Bundle\FrameworkBundle\Routing\Router 的实例

这是我的 services.xml 的样子:

<!-- SessionHandler --> <service id="foo.sessionhandler" class="FooBundle\Service\SessionHandler"> <argument type="service" id="security.http_utils" /> <argument type="collection" id="options" /> <argument type="service" id="router" /> </service>

那么如何让这项服务使用我的定制路由器?

【问题讨论】:

    标签: php symfony dependency-injection routing


    【解决方案1】:

    当前传递的router 是Symfony 路由器,因此给出了Symfony Symfony\Bundle\FrameworkBundle\Routing\Router

    您必须将自定义的Router (FooBundle/Routing/Router) 定义为服务并将其服务ID 传递给服务foo.sessionhandler 的参数列表以替换&lt;argument type="service" id="router" /&gt;

    【讨论】:

    • 我明白了。因此,在 service.xml 中,我必须在上面的问题中为 SessionHandler 定义类似的内容。路由器的构造函数要求一个容器,我知道如何提供,但它也要求加载一个资源。我将如何为路由器服务提供它?
    • 那个资源是什么?如果是从教义中加载的东西,您可以提供@doctrine.orm.entity_manager
    • 我不知道它到底是什么,Symfony 路由器描述中的评论只是说@param mixed $resource The main resource to load
    • 最简单的了解方法是尝试转储并查看您获得的资源对象。然后检查该资源是否在服务中可用。
    猜你喜欢
    • 1970-01-01
    • 2015-08-03
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    相关资源
    最近更新 更多