HTTP Responses

Response to be returned

[Since 0.5.0]

The Pletfix HTTP Response class based on Flight, an extensible micro-framework. It's open-sourced software licensed under the MIT license.

Introduction

The Response class represents an HTTP response. The object contains the response headers, HTTP status code, and response body.

Creating HTTP Responses

All routes and controllers should return a response to be sent back to the user's browser.

The simplest way to return responses is returning a string from a route or controller:

$route->get('hello', function () {
    return 'Hello World';
});

The framework will automatically convert the string into a full HTTP response.

Another way is returning a full Response instance directly from a route or controller. You can create a Response instance via Dependency Injector:

$route->get('hello', function () {
    /** @var \Core\Services\Contracts\Response $response */
    $response = DI::getInstance()->get('response');
    return $response->output('Hello World');
});

The shortcut is the global function response() to creating a Response instance:

$route->get('hello', function () {
    return response()->output('Hello World');
});

Returning a full Response instance allows you to customize the response's HTTP status code and headers:

$route->get('hello', function () {
    return response->output('Hello World', 200, ['Content-Type' => 'text/plain']);
});

Available Methods

The Response object has these methods:

Method Listing

back()

The back method gets a redirect to the previous page on which the user clicked a link to the current page.

return response()->back();

You can specify a fallback url that is used if the HTTP_REFERER is not set in the request header because the user did not clicked a link before:

return response()->back('home');         

See also the redirect method.

cache()

The cache sets caching headers for the response:

response()->cache(false); // no-cache

response()->cache('2017-02-25 00:00:00);

clear()

The clear method clears the response:

response()->clear();

getContent()

The getContent method returns the content from the response:

$content = response()->getContent();

getHeader()

The getHeader method returns the header from the response:

$header = response()->getHeader();

$url = response()->getHeader('location');

getStatusCode()

The getStatusCode method gets the HTTP status code:

echo response()->getStatusCode();

getStatusText()

The getStatusText gets the HTTP status text:

echo response()->getStatusText();

header()

The header method adds a header to the response:

return response()->output($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value')
            ->header('X-Header-Two', 'Header Value');

json()

The json method gets a JSON response:

return response()->json($data);         

download()

The download method gets a file download response:

return response()->download($pathToFile);

You may set a file name as the second argument that is seen by the user downloading the file:

return response()->download($pathToFile, $name);


If you like to display the file directly in the browser, use the file method instead.

file()

The file method gets the raw contents of a binary file. It may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download.

return response()->file($pathToFile);


If you like initiating a download, use the download method instead.

output()

The output method sets the output:

echo response()->output('foo');          

You can set the response's status and headers as like as:

return response()->output('foo, ['a' => 4711], 200, ['Content-Type' => 'text/plain']);   

plaintext()

The plaintext method gets a plaintext response:

return response()->plaintext('Hello World!);  

redirect()

The redirect method returns a redirect HTTP response to the given URL:

$redirect = response()->redirect(url('home'));

The default HTTP status is 302 for a temporarily link. You can create a permanently redirekt like this:

$redirect = response()->redirect(url('home'), 301);   


Note, there is also helper function to create a redirect response:

$redirect = redirect('home');

send()

Sends a HTTP response:

response()->send();   

Fhe Framework will execute this method automatically, so you don't call this method explicitly!

status()

The status method sets the HTTP status code:

response()->status(Response::HTTP_NOT_FOUND);     

view()

The view method renders the output by the given view:

return response()->view($name);   

If you need control over the response's status and headers but also need to return a view as the response's content, you should use the view method:

return response()->view($name, $variables = [], 200, ['Content-Type' => 'text/plain']);   

Of course, if you do not need to pass a custom HTTP status code or custom headers, you should use the global view helper function:

return view($name);   

withFlash()

The withFlash method flashes a piece of data to the session:

return response()->withFlash('foo', 'bar');   

An array is not overridden but merged with the flash data:

return response()
    ->withFlash('foo', ['bar', 'baz'])
    ->withFlash('foo', ['boo']); // foo = ['bar', 'baz', 'boo']   

withInput()

The withInput method flashes an array of input to the session:

return response()->withInput($input);   

You may omit the argument to flash all of the current input:

return response()->withInput();   

Use the old() function during the subsequent HTTP request to retrieve the input from the flash:

$email = old('email);

withMessage()

The withMessage method flashes a message to the session:

return response()->withMessage('Operation successfull.');

Use the message() function during the subsequent HTTP request to retrieve the message from the flash:

$message = message();

withError()

The withError method flashes an error message to the session:

return response()->withError('Operation failed.');   

If the error is related to a input field, you may set the fields name as second argument:

return response()->withError('The e-mail is invalid.', 'email');   

Use the error() function during the subsequent HTTP request to retrieve the error message from the flash:

$error = error('email');

withErrors()

The withErrors method flashes a list of error messages to the session:

return response()->withErrors([
    'email'    => 'The e-mail is invalid.',
    'password' => 'The password is required.',
]);   

Use the error() function during the subsequent HTTP request to retrieve the error message from the flash:

$error = error();

write()

The write method contents to the response body:

return response()->write('foo');   

(edit on GitHub)