在Symfony2中转发内部服务

时间:2013-08-13 12:44:27

标签: symfony service containers forward

我想在服务中使用forward()方法。我将http_kernel定义为我服务的参数,但是我收到了这个错误:

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',
    ));
}

2 个答案:

答案 0 :(得分:4)

Symfony\Component\HttpKernel\HttpKernel对象没有方法forward。这是Symfony\Bundle\FrameworkBundle\Controller\Controller的方法 这就是您收到此错误的原因 作为旁注,您不应该对构造函数进行任何计算。最好创建一个process方法,该方法在之后立即调用。

这是另一种方法:

services.yml

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

注意scope: request是必填参数,以便为您的对象提供@request服务。

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);
    }
}

答案 1 :(得分:2)

您可以通过将容器注入服务然后添加如下所示的转发功能来完成此操作。

<强> services.yml

 my.service:
     class: MyProject\MyBundle\MyService
     arguments: ['@service_container']

<强> MyService.php

use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class MyService
{
    private $container;

    function __construct(Container $container)
    {
        $this->container = $container;     
    }

    public function forward($controller, array $path = array(), array $query = array())
    {
        $path['_controller'] = $controller;
        $subRequest = $this->container->get('request_stack')->getCurrentRequest()->duplicate($query, null, $path);

        return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
    }

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