Wolff\Core\Http\Response
New responses can be made throught the Wolff Response class. It implements the Wolff\Core\Http\ResponseInterface
interface.
This can be done to avoid the superglobals of PHP, giving you a more object oriented syntax.
This response object is the one that must be passed as second parameter to the Controller's public functions, route functions, and middleware functions.
Route::get('/', function($request, $response) {
});
Route::code(404, function($request, $response) {
});
Middleware::before('/', function($request, $response) {
});
namespace Controller;
class Home extends Controller
{
public function index($request, $response)
{
}
}
After the current controller method or route function is finished, the send
method of the response object is called automatically, meaning that you don't have to worry about calling it in your code.
Creating a new Response.
$response = new Wolff\Core\Http\Response();
All of the response methods can be chained, making the process easier and quicker.
$response->setHeader('Content-Type', 'text/html; charset=utf-8')
->write('Hello world')
->setCode(200)
->setCookie('logged_in', 'yes')
->send();
write($content)
Sets the content that will be returned by the response.
$response->write('Hello world');
That would be the equivalent to the classic and ugly: echo 'hello world';
.
The string value of the given variable is the one that will be returned.
append($content)
Appends content to the current content that will be returned by the response.
$response->append('How are you?');
The string value of the given variable is the one that will be returned.
get()
Returns the current content of the response.
$response->get();
setCode([int $status])
Sets the HTTP status code.
$response->setCode(200);
setHeader(string $key, string $value)
Adds a new header to the response.
$response->setHeader('Content-Type', 'text/html');
setCookie(string $key, string $value[, $time[, string $path[, string $domain[, bool $secure[, bool $http_only]]]]])
Adds a new cookie to the response.
$response->setCookie('has_recent_activity', '1');
More expresive example.
$response->setCookie('user_session', 'Zcv6ys3dgluw', 60, '/', true, true);
unsetCookie(string $key)
Removes a cookie.
$response->unsetCookie('user_session');
send([bool $return])
Sends the response with all of its values.
$response->send();
If you pass a true
value as parameter, the method will return the response content instead of printing it out.
$content = $response->send(true);