1

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

これを行うには、コンテナーをサービスに挿入してから、以下のような転送機能を追加します。

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',
        ));
    }
}
于 2016-11-15T10:29:42.413 に答える