Response
The Response
object is used to return the HTTP response. It allows you to control the content, headers, and status of the response sent to the client. Here are the basics for using the Response
object:
Creating an instance of
Response
:use Qwwwest\Namaskar\Response; $response = new Response();
Modifying the response content: For example, to set the response content as a string, you use the
setContent($string)
method:$response->setContent('Response content');
You can also use specific formats such as JSON with the appropriate method json($array)
, or more generally the file($filename)
function, for example file('styles.css')
, the appropriate header will be added.
Setting response headers: You can add HTTP headers to the response using the
setHeader()
method. For example, to set aContent-Type
header with the valueapplication/json
, you can use:$response->setHeader('Content-Type', 'application/json');
In the case of a
Content-Type
header with the valueapplication/json
, you can also use thesetContentType($type)
function:$response->setContentType('json');
The supported content types are: json, text, css, javascript, html, jpeg, png, gif, svg, xml.
Setting the response status code: You can specify the HTTP status code of the response using the
setStatusCode($code)
method. For example, to set the200 OK
status code, you can use:$response->setStatusCode(200);
You can also use common status codes such as
404
, etc.To redirect to another page, you can simply use the
redirect($url)
method:$response->redirect('/');
Returning the response: Once you have configured the content, headers, and status code of the response, you need to return it to the client using the
return
method:return $response;
There are other advanced features and methods for handling HTTP responses, including managing cookies, redirection, etc.