Creating JSONP(adding) responses with Silex
This blog post was published more than one year ago and might be outdated!
· One min read
Recently I had the need to extend a Silex application to be able to return JSONP responses when needed. I was looking for a generic approach and came across a blog post by Raphael Stolt who solved the problem with a clever "after middleware". This is the code you need to add to your app.php file:
<?php
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('Content-Type');
$jsonpContentTypes = array(
'application/json',
'application/json; charset=utf-8',
'application/javascript',
);
if (!in_array($contentType, $jsonpContentTypes)) {
// Don't touch the response
return;
}
if ($res instanceof JsonResponse) {
$res->setCallBack($req->get('jsonp_callback'));
} else {
$res->setContent($req->get('jsonp_callback')
. '(' . $res->getContent() . ');'
);
}
}
});
You just need to add the code above and everything else will work magically if your request contains a jsonp_callback variable and you returned JSON content in your controller function.