Responses
https://secure.gravatar.com/avatar/b28e536690cbbcc42568497fe280b4f4.png?d=wavatar&s=28
Wed Jul 07 07:36 Authored by zegenie

By default, Pachno handles serving regular html responses without any need for custom code. As long as the template file is present and named correctly, Pachno will run the corresponding controller method and return the associated template.

Sometimes, however, you're likely to want to do something else, such as return a JSON-encoded response or perhaps serve a file.

Returning content that is not html

As long as your controller doesn't return a value, Pachno will handle serving the response from the associated html template. If you want to return something that isn't html, tell Pachno that your controller returns something else:

<?php

use \pachno\core\framework;

// Inside the controller class

public function runCheckUpdates(framework\Request $request): framework\JsonOutput
{
}

public function isOnline(framework\Request $request): framework\TextOutput
{
}

Returning JSON via renderJSON()

Handling JSON in php is fairly straightforward, so you can almost just return json_encode($data) from your controller if you want to. However, returning it via the renderJSON() method ensures that error handling, http headers and layout template wrapping is taken care of.

This is how you return json from your controller via the renderJSON() method:

<?php

use \pachno\core\framework;

// inside the controller class

public function runCheckUpdates(framework\Request $request): framework\JsonOutput
{
  return $this->renderJSON(
    ['version' => framework\Context::getVersion()]
  );
}

The controller renderJSON() method is just a shortcut to instantiating a new framework\JsonOutput object and returning it, so you can also do this:

<?php

use \pachno\core\framework;

// inside the controller class

public function runCheckUpdates(framework\Request $request): framework\JsonOutput
{
  return new framework\JsonOutput(
    ['version' => framework\Context::getVersion()]
  );
}

Note: If your response data is an array which contains an error element, the JsonOutput object will automatically set http status 400 Bad Request on the response object (not the JsonOutput object). You can override this behaviour by returning an instantiated JsonOutput object, but changing the response object http status after instantiating and before returning the JsonOutput object:

<?php

use \pachno\core\framework;

// inside the controller class

public function runCheckUpdates(framework\Request $request): framework\JsonOutput
{
  $json = new framework\JsonOutput(
    ['error' => 'Version information not found']
  );

  $this->getResponse()->setHttpStatus(Response::HTTP_STATUS_OK);

  return $json;
}

Returning plain text via renderText()

Sometimes you don't even need to return JSON, a simple text response will do. For this, use the renderText() method. The renderText() method - like the renderJSON() method - will take care of setting the correct response type and template wrapping for you.

<?php

use \pachno\core\framework;

// inside the controller class

public function runIsOnline(framework\Request $request): framework\TextOutput
{
  return $this->renderText('ok');
}

Manipulating the response

You have full access to the response Pachno will be sending via the Response object. In the controller you retrieve this through the getResponse() method. In templates, the response is available via the $pachno_response template variable. The controller method and the template variable returns a framework\Response object, which lets you read, manipulate or change the response as needed.

Changing the http response code

You can change the http response code using the setHttpStatus() method. The Response object has a few shortcut constants for the most used status codes to make your code more readable, but using the status code numbers directly is fine:

<?php

// inside the controller class

// This is fine
$this->getResponse()->setHttpStatus(framework\Response::HTTP_STATUS_BAD_REQUEST);
$this->getResponse()->setHttpStatus(framework\Response::HTTP_STATUS_OK);

// This is also fine
$this->getResponse()->setHttpStatus(418);

Automatically setting the response content type

Pachno will try and auto-detect the response content type based on the http Accept header, and adjust the response type accordingly. If you want to trigger a specific response type, you can also use the :format named request parameter. If this is present in your url or via the @Parameters annotation, Pachno will try and detect the correct response type, read the correct template and return the correct response content type.

Note the :format named parameter in the url in the below @Route example

<?php

  namespace \pachno\modules\hello_world\controllers;

  class Main extends \pachno\core\framework\Action
  {

    /**
     * @Route(name="item", url="/items.:format")
     */
    public function runIndex(\pachno\core\framework\Request $request)
    {
      if (!in_array($format, ['xml', 'json', 'csv']) {
        return $this->return404('This format is not supported');
      }
    }

  }

// The method above should have the following template files
// modules/
//   hello_world/
//     templates/
//       items.csv.php
//       items.json.php
//       items.xml.php

Pachno supports and automatically detects the following formats:

Format Response type
rss, xml application/xml
xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
ods application/vnd.oasis.opendocument.spreadsheet
json application/json
csv text/csv
default text/html

Manually setting the response content type

Sometimes you will want to manually override or set the response content type. Do this using the setContentType() method on the response object.

<?php

// in controller classes
$this->getResponse()->setContentType('application/json');

// in templates
$pachno_response->setContentType('application/xml');

Disabling or changing the response template decoration

By default - and if you don't use the framework\TextOutput or framework\JsonOutput objects - Pachno "decorates" (wraps) the corresponding html template in the global layout template. To disable this, change the response decoration:

<?php

// inside the controller class

// This disables the template decoration
$this->getResponse()->setDecoration(framework\Response::DECORATE_NONE);

You can also customize the response template decoration with a custom header and/or footer template

<?php

// inside the controller class

// Only decorate the response template with a custom header
$this->getResponse()->setDecoration(framework\Response::DECORATE_HEADER, ['header' => '/path/to/template_header.php']);
// or
$this->getResponse()->setDecoration(framework\Response::DECORATE_CUSTOM, ['header' => '/path/to/template_header.php']);

// Only decorate the response template with a custom header
$this->getResponse()->setDecoration(framework\Response::DECORATE_FOOTER, ['footer' => '/path/to/template_footer.php']);
// or
$this->getResponse()->setDecoration(framework\Response::DECORATE_CUSTOM, ['footer' => '/path/to/template_footer.php']);

// Decorate the response template with a custom header and footer
$this->getResponse()->setDecoration(framework\Response::DECORATE_CUSTOM, ['header' => '/path/to/template_header.php', 'footer' => '/path/to/template_footer.php']);

Setting the response html title

Change the html title in the response using the Response::setTitle() method:

<?php

// inside the controller class
$this->getResponse()->setTitle('Boards list');

// inside templates
$pachno_response->setTitle('Boards list');

Adding custom javascript or css

If you want to add or remove javascript or css assets, you can do this via the addJavascript() or addStylesheet() methods:

<?php

// inside the controller class
$this->getResponse()->addStylesheet($this->getRouting()->generate('asset_module_css', ['module_name' => 'hello_world', 'css' => 'admin.css']));

// inside templates
$pachno_response->addStylesheet(make_url('asset_module_css', ['module_name' => 'hello_world', 'css' => 'admin.css']));

Note: Pachno will automatically include your module css or javascript files. If your module contains a public/ folder, Pachno will automatically add the files css/modulename.css and js/modulename.js if they exist. You don't need to add these manually.

Managing cookies

You can set and/or delete cookies using the corresponding setCookie() and deleteCookie() methods. These methods behave similar to the php setcookie() method, but take care of things like setting the correct expiration time, cookie path and more.

<?php

// set a cookie
framework\Context::getResponse()->setCookie('cookie_banner_closed', 1);

// remove a cookie
framework\Context::getResponse()->deleteCookie('cookie_banner_closed');

// set a cookie that only lasts for the duration of the session
framework\Context::getResponse()->setSessionCookie('cookie_banner_closed', 1);

Note: Remember that cookies are only processed on each request and the following response. If you set a cookie, you will only be able to read it on the next request. The same goes for removing cookies - this is also only visible on the next request.

Attachments 0

Comments 0

/unthemed/mono/no-comments.png
Expand, collaborate and share
Post a comment and get things done