JSONP callbacks

To make life a bit easier on callbacks for JSONP requests, the middleware \Enovision\Slim\Jsonp\Middleware\Jsonp can be used. You simply add this middleware to your route and it will create the JSONP required output with callback.

Standard usage

use \Enovision\Slim\Jsonp\Middleware\Jsonp;

$app->post('/parameters/headers', function ($request, $response, $args) {
   ... your code ...     
})->add(new Input([
        ... your input definition ...
])->add(new Jsonp);

When attached to your route, it will expect a callback (default= "callback") parameter in your request. You don't have to define it in your Input middleware, that is taken care of.

Alternate callback definition

If you like you could change the default "callback" tag with something fitting your own requirements by defining it like this:

use \Enovision\Slim\Jsonp\Middleware\Jsonp;

$app->post('/parameters/headers', function ($request, $response, $args) {
   ... your code ...     
})->add(new Input([
   ... your input definition ...
])->add(new Jsonp('someOtherCallbackTag'));

In that case this middleware expects that the request also contains this callback tag in your request.

In case the callback tag is missing, it will be consumed as if an error has occurred and it will return the error array shown earlier.

JSONP in a group router

This middleware also works in group router. The JSON will be applied to all the routes.

use Enovision\Slim\Input\Middleware\Input;
use Enovision\Slim\Jsonp\Middleware\Jsonp;
use App\Helpers\Util;

$app->group( '/movies', function () {

    $this->get( '/BoxOffice', function ( $request, $response ) {
        $postman = $request->getAttribute( 'input.Postman' );

        if ( $postman->hasErrors() ) {
            $feedback = $postman->Error();
        } else {
            $feedback = ['success' => true, 'message' => 'Super, everything is fine'];
        }

        return Util::Response($feedback, $response);

    } )->add( new Input( [
        'level' => 'controller',
    ]) );

} )->add( new Input( [
    'start' => 0,
    'limit' => 50
] ) )->add( new Jsonp( 'cbJSON' ) );
Last update: Tue, 13 Sep 2022 14:32:15