phpsymfonysymfony4php-7.1

Call to protected method Symfony\Bundle\FrameworkBundle\Controller\Controller::generateUrl()


Recently I am upgrading the system to Symfony 4.2, in one of my page, I encountered the error saying

Call to protected method Symfony\Bundle\FrameworkBundle\Controller\Controller::generateUrl() from context 'Acme\Bundle\Security\Listener\SecurityListener'

The line at which the error is showing:

$this_url = $controller[0]->generateUrl($event->getRequest()->get('_route'), $event->getRequest()->get('_route_params'));

Please let me know, is there anything that I have left.


Solution

  • You are trying to call the controller helper method from a listener. As @ArtisticPhoenix has said in the comments, this is not allowed. What you could do here is instead rewrite your listener to use not the controller's method (which is just intended to be a helper for your actions), but the actual router method that generates the URL. Take a look at the Controller (or ControllerTrait depending on your Symfony version). The generateUrl() method makes a call on the @router service:

    /**
     * Generates a URL from the given parameters.
     *
     * @see UrlGeneratorInterface
     *
     * @final
     */
    protected function generateUrl(string $route, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
    {
        return $this->container->get('router')->generate($route, $parameters, $referenceType);
    }
    

    That's what you actually have to use instead of calling the controller's method. You could try something like this:

    $this_url = $this->container->get('router')->generate($event->getRequest()->get('_route'), $event->getRequest()->get('_route_params'));
    

    Although, you'd have to make sure you either have the container available (which in general is not a good pattern), or you pass the Router into your service as a dependency. This way, you'd change $this->container->get('router') to the prop you're injecting the router into.