Skip to content

Instantly share code, notes, and snippets.

@dmouse
Last active July 20, 2021 17:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dmouse/c7ac15e96dc216ad2f12 to your computer and use it in GitHub Desktop.
Save dmouse/c7ac15e96dc216ad2f12 to your computer and use it in GitHub Desktop.
Return a Symfony Response Object in Drupal 9 and Drupal 8
<?php
namespace Drupal\response\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends ControllerBase
{
/**
* hello
* @param string $name
* @return string
*/
public function hello($name) {
$response = new Response();
$response->setContent('Hello ' . $name);
$response->setMaxAge(10);
return $response;
}
}
name: Response example
type: module
description: 'Return a Response Object in Drupal 8'
core: 8.x
package: Other
response.hello:
path: '/response/hello/{name}'
defaults:
_content: '\Drupal\response\Controller\DefaultController::hello'
_title: 'response Title'
requirements:
_permission: 'access content'
@chrishappy
Copy link

Don't forget use Symfony\Component\HttpFoundation\Response; in the controller file :)

@gwagroves
Copy link

Or use \Drupal\Core\Cache\CacheableResponse, which extends \Symfony\Component\HttpFoundation\Response adding support for cacheability meta data.

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