The majority of responses in my application are either views or JSON. I can't figure out how to put them in objects that implement ResponseInterface
in PSR-7.
Here is what I currently do:
// Views
header('Content-Type: text/html; charset=utf-8');
header('Content-Language: en-CA');
echo $twig->render('foo.html.twig', array(
'param' => 'value'
/* ... */
));
// JSON
header('Content-Type: application/json; charset=utf-8');
echo json_encode($foo);
Here is what I am attempting to do with PSR-7:
// Views
$response = new Http\Response(200, array(
'Content-Type' => 'text/html; charset=utf-8',
'Content-Language' => 'en-CA'
));
// what to do here to put the Twig output in the response??
foreach ($response->getHeaders() as $k => $values) {
foreach ($values as $v) {
header(sprintf('%s: %s', $k, $v), false);
}
}
echo (string) $response->getBody();
And I suppose it would be similar for the JSON response just with different headers. As I understand the message body is a StreamInterface
and it works when I try to output a file resource created with fopen
but how do I do it with strings?
Update
Http\Response
in my code is actually my own implementation of the ResponseInterface
in PSR-7. I have implemented all of the interfaces as I am currently stuck with PHP 5.3 and I couldn't find any implementations that were compatible with PHP < 5.4. Here is the constructor of Http\Response
:
public function __construct($code = 200, array $headers = array()) {
if (!in_array($code, static::$validCodes, true)) {
throw new \InvalidArgumentException('Invalid HTTP status code');
}
parent::__construct($headers);
$this->code = $code;
}
I can modify my implementation to accept the output as a constructor argument, alternatively I can use the withBody
method of the MessageInterface
implementation. Regardless of how I do it, the issue is how to get a string into a stream.