Skip to content

Instantly share code, notes, and snippets.

@sarelvdwalt
Created June 1, 2015 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarelvdwalt/db25320aebec8559dc1f to your computer and use it in GitHub Desktop.
Save sarelvdwalt/db25320aebec8559dc1f to your computer and use it in GitHub Desktop.
Symfony Response Object that creates a JSON object which envelopes your content in a "content" part and has "meta" data that you can add on to. I tuses the JMSSerializerBundle to make sure it serializes properly.
<?php
/**
* User: sarel
* Date: 2015/05/31
* Time: 10:10 AM
*/
namespace AH\AQueueBundle\Helper;
use JMS\Serializer\SerializerBuilder;
use Symfony\Component\HttpFoundation\Response;
class ResponseJSON extends Response
{
/**
* Constructor.
*
* @param mixed $content The response content, see setContent()
* @param int $status The response status code
* @param array $headers An array of response headers
*
* @throws \InvalidArgumentException When the HTTP status code is not valid
*
* @api
*/
public function __construct($content = '', $status = 200, $headers = array(), $extra_meta = array())
{
parent::__construct('', 200, array('Content-Type' => 'application/json'));
$meta = array_merge(array('status'=>$status), $extra_meta);
$serializer = SerializerBuilder::create()->build();
$json = $serializer->serialize(
array(
'content' => $content,
'meta' => $meta
), 'json');
$this->setContent($json);
$this->setStatusCode($status);
}
}
@sarelvdwalt
Copy link
Author

Usage:

$content = array('foo'=>'bar');
$extraMeta = array('tell_the_user'=>'something');
return new ResponseJSON($content, Response::HTTP_OK, null, $extraMeta);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment