Response

The response represents the server's HTTP response to the client. There are a couple of different types, listed below, each with an example of how the response from the controller action is built.

String

To return a simple string response, use the response service.

  1. public function indexAction()
  2. {
  3. return $this['response']->create('My content');
  4. }

Rendered View

Pagekit can render the view and return the response for you. Simply return an array, with a key $view set to an array containing a title and a view name.

All other parameters in the array, will be accessible in the view. Learn more about Views and Templating.

  1. public function indexAction($name = '')
  2. {
  3. return [
  4. '$view' => [
  5. 'title' => 'Hello World',
  6. 'name' => 'hello:views/index.php',
  7. ],
  8. 'name' => $name
  9. ];
  10. }

If you don't want this to render a themed response as explained below, set 'layout' => false in the $view array.

Themed

A themed response embeds the controller's result within a surrounding layout, usually defined by the theme. Simply return a string from the controller.

  1. public function indexAction()
  2. {
  3. return 'My content';
  4. }

JSON

There are two ways to return a JSON response from the controller:

If the action either returns an array or an object that implements \JsonSerializable, a JsonResponse will be generated automatically.

  1. public function jsonAction()
  2. {
  3. return ['error' => true, 'message' => 'There is nothing here. Move along.'];
  4. }

Of course, the response service can be used to achieve the same thing.

  1. public function jsonAction()
  2. {
  3. return $this['response']->json(['error' => true, 'message' => 'There is nothing here. Move along.']);
  4. }

Redirect

Use a redirect response to redirect the user.

  1. public function redirectAction()
  2. {
  3. return $this['response']->redirect('@hello/greet/name', ['name' => 'Someone']);
  4. }

Custom response and error pages

Return any custom HTTP response using create.

  1. public function forbiddenAction()
  2. {
  3. return $this['response']->create('Permission denied.', 401);
  4. }

Stream

The streamed response allows to stream the content back to the client. It takes a callback function as its first argument. Within that callback, a call to flush will be emitted directly to the client.

  1. public function streamAction()
  2. {
  3. return $this['response']->stream(function() {
  4. echo 'Hello World';
  5. flush();
  6. echo 'Hello Pagekit';
  7. flush();
  8. });
  9. }

Download

The download response lets you send a file to the client. It sets Content-Disposition: attachment to force a Save as dialog in most browsers.

  1. public function downloadAction()
  2. {
  3. return $this['response']->download('extensions/hello/extension.svg');
  4. }