2021-06-21 1242次浏览

First version of yiisoft/data-response pacakge was released.

The package allows responding with data that is then automatically converted into PSR-7 response using one of the formatters such as JSON or XML.

use Yiisoft\DataResponse\DataResponseFactory;
use Yiisoft\DataResponse\Formatter\JsonDataResponseFormatter;

/**
 * @var Psr\Http\Message\ResponseFactoryInterface $responseFactory
 */

// Usually in controller:
$factory = new DataResponseFactory($responseFactory);
$dataResponse = $factory->createResponse(['best' => 'test']);


// Usually done automatically via one of middleware provided by the pacakge:
$dataResponse = $dataResponse->withResponseFormatter(new JsonDataResponseFormatter());
$dataResponse->getBody()->rewind();

echo $dataResponse->getHeader('Content-Type'); // ["application/json; charset=UTF-8"]
echo $dataResponse->getBody()->getContents(); // {"best": "test"}

There is also a middleware for negotiating content so formatter could be chosed based on Content-Type header sent by the client.