psr-7_ http message interfaces - php-fig

Download PSR-7_ HTTP Message Interfaces - PHP-FIG

Post on 28-Feb-2018

213 views

Category:

Documents

0 download

Embed Size (px)

TRANSCRIPT

  • 7/25/2019 PSR-7_HTTP Message Interfaces - PHP-FIG

    1/55

    PHP-FIGHomeRecommendations (PSRs)MembersBylawsFAQsGet InvolvedPSR-7:HTTP message interfacesPSR-7:HTTP message interfaces

    Thisdocument describescommon interfacesforrepresenting HTTP

    messagesasdescribedin RFC 7230andRFC 7231, andURIsforuse with HTTP

    messagesasdescribedin RFC 3986.

    HTTP messagesare the foundation of web development. Web browsersand

    HTTP clientssuch ascURL create HTTP request messagesthat are sent to a

    web server, which providesan HTTP response message. Server-side code

    receivesan HTTP request message, andreturnsan HTTP response message.

    HTTP messagesare typically abstractedfrom the end-userconsumer, but as

    developers, we typically needto knowhowthey are structuredandhowto

    accessormanipulate them in orderto perform ourtasks, whetherthat might

    be making a request to an HTTP API, orhandling an incoming request.

    Every HTTP request message hasa specific form:

    ST/pathHTT /1.1

    Host: example.com

    foo=bar&baz=bat

    The first line of a request isthe "request line", andcontains, in order, the

    HTTP request method, the request target (usually eitheran absolute URIora

    path on the web server), andthe HTTP protocol version. Thisisfollowedby

    7: HTTP message interfaces - PHP-FIG http://www.php-fig.org/p

    55 19/06/2016 0

  • 7/25/2019 PSR-7_HTTP Message Interfaces - PHP-FIG

    2/55

    one ormore HTTP headers, an empty line, andthe message body.

    HTTP response messageshave a similarstructure:

    HTT /1.1200 K

    Content-Type: text/plain

    This is the response body

    The first line isthe "statusline", andcontains, in order, the HTTP protocol

    version, the HTTP statuscode, anda "reason phrase," a human-readable

    description of the statuscode. Like the request message, thisisthen followedby one ormore HTTP headers, an empty line, andthe message body.

    The interfacesdescribedin thisdocument are abstractionsaroundHTTP

    messagesandthe elementscomposing them.

    The key words"MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",

    "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and"OPTIONAL" inthisdocument are to be interpretedasdescribedin RFC 2119.

    References

    RFC 2119

    RFC 3986

    RFC 7230

    RFC 7231

    1. Speci cation

    7: HTTP message interfaces - PHP-FIG http://www.php-fig.org/p

    55 19/06/2016 0

  • 7/25/2019 PSR-7_HTTP Message Interfaces - PHP-FIG

    3/55

    1.1Messages

    An HTTP message iseithera request from a client to a serverora response

    from a serverto a client. Thisspecification definesinterfacesforthe HTTP

    messages Psr\Http\Message\RequestInterface and Psr\Http\Message

    \ResponseInterface respectively.

    Both Psr\Http\Message\RequestInterface and Psr\Http\Message

    \ResponseInterface extend Psr\Http\Message\MessageInterface . While

    Psr\Http\Message\MessageInterface MAY be implementeddirectly,

    implementorsSHOULD implement Psr\Http\Message\RequestInterface and

    Psr\Http\Message\ResponseInterface .

    From here forward, the namespace Psr\Http\Message will be omittedwhen

    referring to these interfaces.

    1.2HTTP Headers

    Case-insensitive headerfieldnames

    HTTP messagesinclude case-insensitive headerfieldnames. Headersare

    retrievedby name from classesimplementing the MessageInterface in a

    case-insensitive manner. Forexample, retrieving the foo headerwill return

    the same result asretrieving the FoO header. Similarly, setting the Foo

    headerwill overwrite any previously set foo headervalue.

    $message = $message->withHeader('foo', 'bar');

    echo $message->getHeaderLine('foo');

    // Outputs: bar

    echo $message->getHeaderLine('FOO');

    7: HTTP message interfaces - PHP-FIG http://www.php-fig.org/p

    55 19/06/2016 0

  • 7/25/2019 PSR-7_HTTP Message Interfaces - PHP-FIG

    4/55

    // Outputs: bar

    $message = $message->withHeader('fOO', 'baz');

    echo $message->getHeaderLine('foo');

    // Outputs: baz

    Despite that headersmay be retrievedcase-insensitively, the original case

    MUST be preservedby the implementation, in particularwhen retrievedwith

    getHeaders() .

    Non-conforming HTTP applicationsmay dependon a certain case, so it is

    useful fora userto be able to dictate the case of the HTTP headerswhen

    creating a request orresponse.

    Headerswith multiple values

    In orderto accommodate headerswith multiple valuesyet still provide the

    convenience of working with headersasstrings, headerscan be retrieved

    from an instance of a MessageInterface asan array ora string. Use the

    getHeaderLine() methodto retrieve a headervalue asa string containing all

    headervaluesof a case-insensitive headerby name concatenatedwith a

    comma. Use getHeader() to retrieve an array of all the headervaluesfora

    particularcase-insensitive headerby name.

    7: HTTP message interfaces - PHP-FIG http://www.php-fig.org/p

    55 19/06/2016 0

  • 7/25/2019 PSR-7_HTTP Message Interfaces - PHP-FIG

    5/55

    $message = $message

    ->withHeader('foo', 'bar')

    ->withAddedHeader('foo', 'baz');

    $header = $message->getHeaderLine('foo');

    // $header contains: 'bar, baz'

    $header = $message->getHeader('foo');

    // ['bar', 'baz']

    Note: Not all headervaluescan be concatenatedusing a comma (e.g.,

    Set-Cookie ). When working with such headers, consumersof

    MessageInterface -basedclassesSHOULD rely on the getHeader() methodfor

    retrieving such multi-valuedheaders.

    Host header

    In requests, the Host headertypically mirrorsthe host component of the URI,

    aswell asthe host usedwhen establishing the TCP connection. However, the

    HTTP specification allowsthe Host headerto differfrom each of the two.

    During construction, implementationsMUST attempt to set the Host header

    from a providedURIif no Host headerisprovided.

    RequestInterface::withUri() will, by default, replace the returnedrequest's

    Host headerwith a Host headermatching the host component of the passed

    UriInterface .

    Youcan opt-in to preserving the original state of the Host headerby passing

    true forthe second( $preserveHost ) argument. When thisargument isset to

    true , the returnedrequest will not update the Host headerof the returned

    message -- unlessthe message containsno Host header.

    7: HTTP message interfaces - PHP-FIG http://www.php-fig.org/p

    55 19/06/2016 0

  • 7/25/2019 PSR-7_HTTP Message Interfaces - PHP-FIG

    6/55

    Thistable illustrateswhat getHeaderLine('Host') will return fora request

    returnedby withUri() with the $preserveHost argument set to true for

    variousinitial requestsandURIs.

    REQUESTHOST

    HEADER1

    REQUESTHOST

    COMPONENT2

    URIHOST

    COMPONENT3

    RESULT

    '' '' '' ''

    '' foo.com '' foo.com

    '' foo.com bar.com foo.com

    foo.com '' bar.com foo.com

    foo.com bar.com baz.com foo.com

    1 Host headervalue priorto operation.

    2Host component of the URIcomposedin the request priorto the

    operation.

    3Host component of the URIbeing injectedvia withUri() .

    1.3Streams

    HTTP messagesconsist of a start-line, headers, anda body. The body of an

    HTTP message can be very small orextremely large. Attempting to represent

    the body of a message asa string can easily consume more memory than

    intendedbecause the body must be storedcompletely in memory.

    Attempting to store the body of a request orresponse in memory would

    preclude the use of that implementation from being able to work with large

    message bodies. StreamInterface isusedin orderto hide the implementation

    detailswhen a stream of data isreadfrom orwritten to. Forsituationswhere

    a string wouldbe an appropriate message implementation, built-in streams

    such as php://memory and php://temp may be used.

    7: HTTP message interfaces - PHP-FIG http://www.php-fig.org/p

    55 19/06/2016 0

  • 7/25/2019 PSR-7_HTTP Message Interfaces - PHP-FIG

    7/55

    StreamInterface exposesseveral methodsthat enable streamsto be read

    from, written to, andtraversedeffectively.

    Streamsexpose theircapabilitiesusing three methods: isReadable() ,

    isWritable() , and isSeekable() . These methodscan be usedby stream

    collaboratorsto determine if a stream iscapable of theirrequirements.

    Each stream instance will have variouscapabilities: it can be read-only,

    write-only, orread-write. It can also allowarbitrary random access(seeking

    forwardsorbackwardsto any location), oronly sequential access(for

    example in the case of a socket, pipe, orcallback-basedstream).

    Finally, StreamInterface definesa __toString() methodto simplify retrieving

    oremitting the entire body contentsat once.

    Unlike the request andresponse interfaces, StreamInterface doesnot model

    immutability. In situationswhere an actual PHP stream iswrapped,

    immutability isimpossible to enforce, asany code that interactswith the

    resource can potentially change itsstate (including cursorposition, contents,andmore). Ourrecommendation isthat implementationsuse read-only

    streamsforserver-side requestsandclient-side responses. Consumers

    shouldbe aware of the fact that the stream instance may be mutable, and, as

    such, couldalterthe state of the message; when in doubt, create a new

    stream instance andattach it to a message to enforce state.

    1.4 Request TargetsandURIs

    PerRFC 7230, request m