1

我想在forward()服务内部使用该方法。我定义http_kernel为我的服务的参数,但我得到这个错误:

FatalErrorException: Error: Call to undefined method forward()

配置.yml:

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

我的服务.php:

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

2 回答 2

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);
    }
}
于 2013-08-13T12:58:00.320 回答
2

您可以通过将容器注入到您的服务中来做到这一点,然后添加如下所示的转发功能。

服务.yml

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

我的服务.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',
        ));
    }
}
于 2016-11-15T10:29:42.413 回答