Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PSR-7 responses?

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.

like image 266
rink.attendant.6 Avatar asked Oct 30 '22 15:10

rink.attendant.6


1 Answers

ResponseInterface extends MessageInterface, which provides the getBody() getter you've found. PSR-7 expects the object implementing ResponseInterface to be immutable, which you will not be able to achieve without modifying your constructor.

As you are running PHP < 5.4 (and can't type-hint effectively), modify it as follows:

public function __construct($code = 200, array $headers = array(), $content='') {
  if (!in_array($code, static::$validCodes, true)) {
    throw new \InvalidArgumentException('Invalid HTTP status code');
  }

  parent::__construct($headers);
  $this->code = $code;
  $this->content = (string) $content;
}

Define a private member $content as follows:

private $content = '';

And a getter:

public function getBody() {
  return $this->content;
}

And you're good to go!

like image 193
Sébastien Renauld Avatar answered Nov 15 '22 06:11

Sébastien Renauld