The PSR-7 Bridge

The PSR-7 Bridge

The PSR-7 bridge converts HttpFoundation objects from and to objects implementing HTTP message interfaces defined by the PSR-7.

Installation

You can install the component in 2 different ways:

The bridge also needs a PSR-7 implementation to allow converting HttpFoundation objects to PSR-7 objects. It provides native support for Zend Diactoros. Use Composer (zendframework/zend-diactoros on Packagist) or refer to the project documentation to install it.

Usage

Converting from HttpFoundation Objects to PSR-7

The bridge provides an interface of a factory called HttpMessageFactoryInterface that builds objects implementing PSR-7 interfaces from HttpFoundation objects. It also provide a default implementation using Zend Diactoros internally.

The following code snippet explain how to convert a Request to a Zend Diactoros ServerRequest implementing the ServerRequestInterface interface:

1
2
3
4
5
6
7
8
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
use Symfony\Component\HttpFoundation\Request;

$symfonyRequest = new Request(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'dunglas.fr'), 'Content');
// The HTTP_HOST server key must be set to avoid an unexpected error

$psr7Factory = new DiactorosFactory();
$psrRequest = $psr7Factory->createRequest($symfonyRequest);

And now from a Response to a Zend Diactoros Response implementing the ResponseInterface interface:

1
2
3
4
5
6
7
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
use Symfony\Component\HttpFoundation\Response;

$symfonyResponse = new Response('Content');

$psr7Factory = new DiactorosFactory();
$psrResponse = $psr7Factory->createResponse($symfonyResponse);

Converting Objects implementing PSR-7 Interfaces to HttpFoundation

On the other hand, the bridge provide a factory interface called HttpFoundationFactoryInterface that builds HttpFoundation objects from objects implementing PSR-7 interfaces.

The next snippet explain how to convert an object implementing the ServerRequestInterface interface to a Request instance:

1
2
3
4
5
6
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;

// $psrRequest is an instance of Psr\Http\Message\ServerRequestInterface

$httpFoundationFactory = new HttpFoundationFactory();
$symfonyRequest = $httpFoundationFactory->createRequest($psrRequest);

From an object implementing the ResponseInterface to a Response instance:

1
2
3
4
5
6
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;

// $psrResponse is an instance of Psr\Http\Message\ResponseInterface

$httpFoundationFactory = new HttpFoundationFactory();
$symfonyResponse = $httpFoundationFactory->createResponse($psrResponse);

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.