Create a custom action result

An action result is a type of class that can be instantiated and returned from a controller to perform various actions on the page result. Some examples are the NotFoundResult, RedirectResult or JsonResult classes.

The source code for the action results included in BlueMvc can be found on Github.

This tutorial will show how to create a custom action result.

The ActionResultInterface

In order to create an action result class, the interface ActionResultInterface must be implemented. This interface has only one method signature:

public function updateResponse(ApplicationInterface $application, RequestInterface $request, ResponseInterface $response): void;

This method will be called when the object is returned from the action method in the controller, and its purpose is (but of course not limited to) update the response object.

Example

A somewhat useful example is an action result that displays the content of a variable in human-readable format.

The action result, called DebugResult, has the following specification:

  1. Pass the variable in the constructor, allowing usage like: return new DebugResult($var);
  2. Do not display anything if not in debug mode, preventing accidental usage on a live site.
  3. Return the result with content type text/plain to display whitespaces as intended.
  4. Set the content to the output of the PHP function print_r for the variable.

The code for this action result might look like this:

<?php declare(strict_types=1); use BlueMvc\Core\Interfaces\ActionResults\ActionResultInterface; use BlueMvc\Core\Interfaces\ApplicationInterface; use BlueMvc\Core\Interfaces\RequestInterface; use BlueMvc\Core\Interfaces\ResponseInterface; class DebugResult implements ActionResultInterface { // 1. Pass the variable in the constructor. public function __construct($var) { $this->var = $var; } public function updateResponse(ApplicationInterface $application, RequestInterface $request, ResponseInterface $response): void { // 2. Do not display anything if not in debug mode. if (!$application->isDebug()) { return; } // 3. Return the result with content type text/plain. $response->setHeader('Content-Type', 'text/plain'); // 4. Set the content to the output of the PHP function print_r. $response->setContent(print_r($this->var, true)); } private $var; }

To try it, insert the following code in an action method:

$var = ['Foo' => 'Bar']; return new DebugResult($var);

If the application is in debug mode, the result should look like this:

Array ( [Foo] => Bar )

✎ Published in category core