Created
June 1, 2015 19:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: