Symfony2 中的转发内部服务

lep*_*pix 1 service containers forward symfony

我想使用forward()服务内部的方法。我定义http_kernel为我的服务的参数,但出现此错误:

FatalErrorException: Error: Call to undefined method forward()
Run Code Online (Sandbox Code Playgroud)

配置.yml:

 my.service:
     class: MyProject\MyBundle\MyService
     arguments: 
        http_kernel: "@http_kernel"
Run Code Online (Sandbox Code Playgroud)

我的服务.php:

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

Tou*_*uki 5

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, [] ]
Run Code Online (Sandbox Code Playgroud)

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