Last Updated: February 25, 2016
· raphaelstolt

JSONP(ad) Silex responses via an after middleware

One approach to auto transform Silex responses into JSONP(adding) responses via an after middleware. It's based on the Content-Type of the original reponse coming from the matching application route.

use Symfony\Component\HttpFoundation\JsonResponse;

$app->after(function (Request $req, Response $res) {
  if ($req->get('jsonp_callback') !== null 
      && $req->getMethod() === 'GET')
    $contentType = $res->headers->get(
    $jsonpContentTypes = array(
      'application/json; charset=utf-8',
    if (!in_array($contentType, $jsonpContentTypes)) 
      // Don't touch the response
    if ($res instanceof JsonResponse) {
    } else {
          . '(' . $res->getContent() . ');'

Another approach would be to guard or compare the current route against a set of JSONPable route patterns, which might come from a configuration; which, however, need to be maintained.

Yet another approach provided by @igorwesome would be to use the native Symfony\Component\HttpFoundation\JsonResponse directly inside a matching route, I guess.

use Silex\Application,

$app->get('/ex', function(Application $a, Request $r) {
  if ($r->get('jsonp_callback') !== null 
      && $r->getMethod() === 'GET')
    $data = $a['service_xy']->getDataXyz();
    $resp = new JsonResponse($data);
    return $resp->setCallback(