简体   繁体   中英

In Symfony sub-request, $this->container is null

I want to implement a batch request api using symfony.
So, I using the sub-request in symfony. But in each controller, the $this->container is null. Because I am using service container in my project.

So, the batch request parameter like below:

{request: [{"url":"/api/user?username=test"},  {"url":"/api/thread?id=123"}]}

And the source code like below:
I want to generate some sub-request to reduce outside HTTP request.

foreach($request_list as $k => $v) {
    parse_str(parse_url($v['url'], PHP_URL_QUERY), $params);
    $req = Request::create(
        parse_url($v['url'], PHP_URL_PATH),
        "POST",
        $params
    );

    $context = new RequestContext();
    $context->fromRequest($req);
    $route = $this->get('router');
    $matcher = new UrlMatcher($route->getRouteCollection(), $context);

    $dispatcher = new EventDispatcher();
    $dispatcher->addSubscriber(new RouterListener($matcher));
    $resolver = new ControllerResolver();
    $kernel = new HttpKernel($dispatcher, $resolver);

    $response = $kernel->handle($req, HttpKernelInterface::SUB_REQUEST);
    $res[$k] = $response->getContent();
}

Can you give my some hints? Thanks!

Why do you want to make simple task so complex?

In your controller you can just create new Request object and pass it to the existing (already instantiated) HttpKernel instance:

foreach($request_list as $k => $v) {
    parse_str(parse_url($v['url'], PHP_URL_QUERY), $params);
    $req = Request::create(
        parse_url($v['url'], PHP_URL_PATH),
        "POST",
        $params
    );

    $httpKernel = $this->container->get('http_kernel');
    $response = $httpKernel->handle(
        $request,
        HttpKernelInterface::SUB_REQUEST
    );
    $res[$k] = $response->getContent();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM