Skip to content

Instantly share code, notes, and snippets.

@Daveiano
Forked from dmouse/SubRequestController.php
Last active February 28, 2020 21:24
Show Gist options
  • Save Daveiano/53d33d84c65fc44a23e2e63cc008f9d1 to your computer and use it in GitHub Desktop.
Save Daveiano/53d33d84c65fc44a23e2e63cc008f9d1 to your computer and use it in GitHub Desktop.
Drupal 8: how to create a sub-request
<?php
namespace Drupal\content_helper\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Class SubRequest.
*
* @package Drupal\content_helper\Controller
*/
class SubRequestController extends ControllerBase implements ContainerInjectionInterface {
/**
* Symfony\Component\HttpKernel\HttpKernelInterface definition.
*
* @var Symfony\Component\HttpKernel\HttpKernelInterface
*/
protected $httpKernel;
/**
* {@inheritdoc}
*/
public function __construct(HttpKernelInterface $http_kernel) {
$this->httpKernel = $http_kernel;
}
/**
* Performs a subrequest.
*
* @param string $path
* Path to use for subrequest.
* @param array $parameters
* The query parameters.
*
* @return string
* The response String.
*
* @throws \Exception
*/
public function subRequest($path, array $parameters = []) {
$sub_request = Request::create($path, 'GET', $parameters);
$subResponse = $this->httpKernel->handle($sub_request, HttpKernelInterface::SUB_REQUEST, FALSE);
return $subResponse->getContent();
}
}
@WesWedding
Copy link

Thanks for sharing this, it was very helpful in working out some issues I had with my own subrequest implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment