Symfony 4.2-如何装饰UrlGenerator

wux*_*ing 5 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
Run Code Online (Sandbox Code Playgroud)

我已将其添加到中,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
Run Code Online (Sandbox Code Playgroud)

仍然不起作用

如何UrlGenerator在Symfony 4.2中装饰?

Fre*_*Bee 5

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

** 服务.yml :

services:
    App\Services\MyRouter:
        decorates: 'router'
        arguments: ['@App\Services\MyRouter.inner']
Run Code Online (Sandbox Code Playgroud)

** 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Jak*_*umi 1

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