Search code examples
symfonyservicecontainersforward

Forward inside Service in Symfony2


I want to use the forward() method inside of a service. I defined http_kernel as argument for my service but I get this error :

FatalErrorException: Error: Call to undefined method forward()

config.yml :

 my.service:
     class: MyProject\MyBundle\MyService
     arguments: 
        http_kernel: "@http_kernel"

MyService.php :

public function __construct($http_kernel) {
    $this->http_kernel = $http_kernel;
    $response = $this->http_kernel->forward('AcmeHelloBundle:Hello:fancy', array(
        'name'  => $name,
         'color' => 'green',
    ));
}

Solution

  • The Symfony\Component\HttpKernel\HttpKernel object has no method forward. It's a method of Symfony\Bundle\FrameworkBundle\Controller\Controller
    This is why you are getting this error.
    As a side note, you should not do any computation into your constructor. Better create a process method which is called immediatly after.

    Here's another way to do this:

    services.yml

    services:
        my.service:
            class: MyProject\MyBundle\MyService
            scope: request
            arguments:
                - @http_kernel
                - @request
            calls:
                - [ handleForward, [] ]
    

    Note: scope: request is a mandatory parameter in order to give the @request service to your object.

    MyProject\MyBundle\MyService

    use Symfony\Component\HttpKernel\HttpKernelInterface;
    use Symfony\Component\HttpFoundation\Request;
    
    class MyService
    {
        protected $request;
        protected $kernel;
    
        public function __construct(HttpKernelInterface $kernel, Request $request)
        {
            $this->kernel  = $kernel;
            $this->request = $request;
        }
    
        public function handleForward()
        {
            $controller = 'AcmeHelloBundle:Hello:fancy';
            $path = array(
                'name'  => $name,
                'color' => 'green',
                '_controller' => $controller
            );
            $subRequest = $this->request->duplicate(array(), null, $path);
    
            $response = $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
        }
    }