Http response object

Swoft's request and response are implemented in the PSR 7 specification. Request and response objects exist in every HTTP request.

  • Request object Request is Swoft\Http\Message\Request
  • The response object Response is Swoft\Http\Message\Response

note!
According to the immutable of the PSR-7 object, all the with* methods are cloned and returned, and must receive new objects for further processing, or use chained calls.

basic method

The PSR-7 interface provides these public methods for request and response objects:

  • withProtocolVersion($version)
  • withHeader($name, $value)
  • withAddedHeader($name, $value)
  • withoutHeader($name)
  • withBody(StreamInterface $body)

The PSR-7 interface provides these methods for response objects:

  • withStatus($code, $reasonPhrase = '')

See PSR-7 for more details and see the specific implementation classes in swowt/http-message

How to get

  • Parameter injection via controller method (Response $response)
  • Get context()->getResponse() by request context
  • Get Swoft\Context\Context::mustGet()->getResponse() by request context Swoft\Context\Context::mustGet()->getResponse() ( deprecated )

Set status code

 $response = \context()->getResponse();
return $response->withStatus(404); 

Output string content

 return $response->withContent("Hello Swoft2.0"); 

Output array

 $data = ['name'=>'Swoft2.0'];
$response->withData($data); 

Output header information

 return $response->withHeader("name","Swoft2.0"); 

Redirect

 // 302
return $response->redirect("http://www.swoft.org",302);

// 404 page
return $response->redirect('/404'); 

document dowload

 return $response->file(\alias('@runtime/1.zip'), "application/octet-stream"); 

Set cookies

 $response = $response->withCookie(’name', 'value');

$response = $response->withCookie(’name', [
    'value'    => 'value3',
    'httpOnly' => true
]); 

Set more than one:

 $cookies = [
    'key1' => 'value1',
    'key2' => [
        'value' => 'value2',
    ],
    'key3' => [
        'value'    => 'value3',
        'httpOnly' => true
    ],
];

$response = $response->withCookies($cookies); 
/docs/2.x/en/http-server/response.html
progress-bar