Writing controllers, manuallyWriting your own filters

Managing URL parameters

Default behaviour

By default, when an action is created, each parameter of the function should be passed in the URL. Here is a sample:

/**
 * My action with 2 compulsory parameters.
 *
 * @URL /test
 * @param string $var1
 * @param string $var2
 */
public function my_action($var1, $var2) { ... } 

In this action, both parameters are compulsory. If one of the parameters is not passed by the user, an error message is displayed. Hopefully, you can get optional parameters using parameters default values:

/**
 * My action with 1 compulsory parameter and one optional.
 *
 * @URL /test
 * @param string $var1
 * @param string $var2
 */
public function my_action($var1, $var2 = 42) { ... } 

In this sample, if the user does not pass the "var2" parameter in the URL, it will be equal to 42. The URL might be: http://[server-url]/[webapp-path]/test?var1=param1

Parameters' type

In classic PHP behaviour, you the @param [type] $var annotation only informs the user of the expected type of the parameter. Using Splash, this annotation means a lot more because Splash will throw an Excpetion if the variable has an unexpected type. For example, if you use the annotation @param int $userId, and the variable is in fact a string ('toto' for instance), an exception will be raised and an HTTP 500 page displayed.

Allowed parameter types are:

  • string
  • int
  • float
  • bool
  • array

Note: with the current version, if a parameter is not valid, an error screen is displayed. You cannot catch this error to provide custom behaviour in the current version. However, you can override the way HTTP 500 errors are displayed (see the "Settings and error handling" part of this documentation).

Injection PSR-7 Request object as a parameter

Splash 7+ has native support for PSR-7 RequestInterface and for ServerRequestInterface objects. The chosen implementation of these interface is the ServerRequest of Zend-Diactoros (https://github.com/zendframework/zend-diactoros/blob/master/doc/book/api.md#serverrequest-message)

This means that Splash will automatically inject a ServerRequest object into your action if your action expects a RequestInterface or a ServerRequestInterface object:

use Psr\Http\Message\ServerRequestInterface;
...

/**
 * My action with the request object filled
 *
 * @URL /test
 * @param ServerRequestInterface $request
 */
public function my_action(ServerRequestInterface $request) {
    $param = $request->getQueryParams()['param'];
    ...
} 

Note: you should use the ServerRequest object instead of accessing directly $_FILES, $_SERVER, $_COOKIES, or HTTP headers.

Writing controllers, manuallyWriting your own filters

Found a typo? Something is wrong in this documentation? Just fork and edit it!