Symfony 4.2-如何装饰UrlGenerator

时间:2019-04-02 06:42:49

标签: php symfony

我想装饰Symfony UrlGenerator类。

Symfony\Component\Routing\Generator\UrlGenerator: ~

my.url_generator:
    class: AppBundle\Service\UrlGenerator
    decorates: Symfony\Component\Routing\Generator\UrlGenerator
    arguments: ['@my.url_generator.inner']
    public:    false

我已将其添加到services.yml中,但是我的AppBundle\Service\UrlGenerator类却被忽略了:

我再次尝试了以下配置。

config/services.yaml

parameters:
    locale: 'en'
    router.options.generator_class: AppBundle\Service\UrlGenerator
    router.options.generator_base_class: AppBundle\Service\UrlGenerator

仍然无法正常工作

如何在Symfony 4.2中装饰UrlGenerator

3 个答案:

答案 0 :(得分:3)

正确的答案是:您不应该装饰UrlGeneratorInterface。 您必须装饰“路由器”服务。在这里检查:https://github.com/symfony/symfony/issues/28663

** services.yml:

services:
    App\Services\MyRouter:
        decorates: 'router'
        arguments: ['@App\Services\MyRouter.inner']

** MyRouter.php:

<?php

namespace App\Services;

use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouterInterface;

class MyRouter implements RouterInterface
{
    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * MyRouter constructor.
     * @param RouterInterface $router
     */
    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    /**
     * @inheritdoc
     */
    public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)
    {
        // Your code here

        return $this->router->generate($name, $parameters, $referenceType);
    }

    /**
     * @inheritdoc
     */
    public function setContext(RequestContext $context)
    {
        $this->router->setContext($context);
    }

    /**
     * @inheritdoc
     */
    public function getContext()
    {
        return $this->router->getContext();
    }

    /**
     * @inheritdoc
     */
    public function getRouteCollection()
    {
        return $this->router->getRouteCollection();
    }

    /**
     * @inheritdoc
     */
    public function match($pathinfo)
    {
        return $this->router->match($pathinfo);
    }
}

答案 1 :(得分:1)

我相信您必须修饰Symfony\Component\Routing\Generator\UrlGeneratorInterface,因为服务应取决于接口而不是特定的实现(类)。

答案 2 :(得分:1)

我认为问题在于UrlGenerator服务名称是Symfony\Component\Routing\Generator\UrlGeneratorInterface,而不是Symfony\Component\Routing\Generator\UrlGenerator(参见this code)。

第二,装饰服务时,装饰器将使用服务名称。因此,您无需修改​​router.options.generator_class

尝试使用此配置:

my.url_generator:
    class: AppBundle\Service\UrlGenerator
    decorates: Symfony\Component\Routing\Generator\UrlGeneratorInterface
    arguments: ['@my.url_generator.inner']

可能不需要将public设置为false,因为在Symfony4 / Flex上,它应该是默认值。