Skip to content

PSR 7: Request Example

Terry L edited this page Jun 20, 2020 · 3 revisions

PSR-7 HTTP Message Interfaces

Namespace

Shieldon\Psr7\Request

Request

__construct($method, $uri, $body, $headers, $version)

  • param string method = "GET" Request HTTP method.
  • param string|UriInterface uri = "" Request URI object URI or URL.
  • param string|StreamInterface body = "" Request body - see setBody()
  • param array headers = [] Request headers.
  • param string version = "1.1" Request protocol version.

Example:

$request = new \Shieldon\Psr7\Request('GET', 'https://www.example.com');

getRequestTarget()

  • return string

In most cases, this will be the origin-form of the composed URI, unless it is changed by withRequestTarget method.

Example:

echo $request->getRequestTarget();
// Outputs: /

withRequestTarget($requestTarget)

  • param string requestTarget *
  • return static

Example:

$request = $request->withRequestTarget('https://www.example2.com/en/');

echo $request->getRequestTarget();
// Outputs: https://www.example2.com/en/

getMethod()

  • return string

Example:

echo $request->getMethod();
// Outputs: GET

withMethod($method)

  • param string method * Case-sensitive method.
  • return static

Example:

$request = $request->withMethod('POST');
echo $request->getMethod();
// Outputs: POST

getUri()

  • return UriInterface

Example:

echo $request->getUri()->getHost();
// Outputs: www.example.com

withUri($uri, $preserveHost)

  • param UriInterface uri * New request URI to use.
  • param string preserveHost * Preserve the original state of the Host header.
  • return static

Example:

$request = new Request('GET', 'https://terryl.in/zh/', '', [], '1.1');

$newRequest = $request->withUri(new Uri('https://play.google.com'));
$newRequest2 = $newRequest->withUri(new Uri('https://www.facebook.com'), true);

echo $newRequest->getUri()->getHost();
// Outputs: play.google.com

echo $newRequest2->getUri()->getHost();
// Outputs: terryl.in
Clone this wiki locally