Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4.2 - How to decorate the UrlGenerator

Tags:

php

symfony

I want to decorate the Symfony UrlGenerator class.

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

I've added this to the services.yml but my AppBundle\Service\UrlGenerator class is ignored:

I tried the following configuration again.

config/services.yaml

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

Still it doesn't work

How to decorate the UrlGenerator in Symfony 4.2?

like image 632
wuxueling Avatar asked Apr 02 '19 06:04

wuxueling


1 Answers

The right answer is : you shouldn't decorate UrlGeneratorInterface. You have to decorate 'router' service. Check here : 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);
    }
}
like image 84
FreezeBee Avatar answered Sep 21 '22 01:09

FreezeBee