Application

The app object conventionally denotes the PHP Express application.

$app = new \Riverside\Express\Application();

delete(string $path, $callback)

Routes HTTP DELETE requests to the specified path with the specified callback function.

$app->delete('/', function ($req, $res) {
    $res->send('DELETE request to homepage');
});

disable(string $name)

Sets the Boolean setting name to false.

$app->disable('trust proxy');

disabled(string $name)

Returns true if the Boolean setting name is disabled (false)

$app->disabled('trust proxy');

enable(string $name)

Sets the Boolean setting name to true.

$app->enable('trust proxy');

enabled(string $name)

Returns true if the setting name is enabled (true).

$app->enabled('trust proxy');

get(string $path, $callback)

Routes HTTP GET requests to the specified path with the specified callback function.

$app->get('/', function ($req, $res) {
    $res->send('GET request to homepage');
});

getRequest()

Return an instance of request object.

$req = $app->getRequest();

getResponse()

Return an instance of response object.

$res = $app->getResponse();

local([string $name = null] [, $value = null])

Get/set local variables to use within the application.

$app->local('name', 'Johnny Bravo'); // setter
$app->local('name'); // return 'Johnny Bravo'
$app->local(); // return all local variables

param($name [, $regex = null])

Add custom parameters to use in a route path.

$app->param('uuid', '[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}');

// Then use in route path
$app->get('ticket/:uuid/', function($req, $res) {
    echo $req->params['uuid'];
});

post(string $path, $callback)

Routes HTTP POST requests to the specified path with the specified callback function.

$app->post('/', function ($req, $res) {
    $res->send('POST request to homepage');
});

put(string $path, $callback)

Routes HTTP PUT requests to the specified path with the specified callback function.

$app->put('/', function ($req, $res) {
    $res->send('PUT request to homepage');
});

render(string $view [, array $locals=array()])

Returns the rendered HTML of a view. It accepts an optional parameter that is an array containing local variables for the view. It is like $res->render(), except it cannot send the rendered view to the client on its own.

$app->render('index');

route(string $path)

Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use $app->route() to avoid duplicate route names (and thus typo errors).

$app->route('/events')
->get(function ($req, $res) {
    $res->render('events');
})
->post(function ($req, $res) {
    $res->json(array('status' => 'OK'));
});

run()

Run the application.

$app->run();

set(string $field [, $value])

Assigns setting name to value.

$app->set('title', 'My Site');

use(string $path, $callback)

Mounts the specified middleware function at the specified path: the middleware function is executed when the base of the requested path matches path.

// If miss to specify a path, will mount the middleware on every request
$app->use(function ($req, $res) {
    $res->header('X-Frame-Options', 'DENY');
    $res->header('X-Content-Type-Options', 'nosniff');
});

// Will mount the middleware only if path match the specified pattern
$app->use('users/edit/:id/', function ($req, $res) {
    $res->header('Access-Control-Allow-Origin', '*');
});

Request

Properties

app

This property holds a reference to the instance of the PHP Express application that is using the middleware.

$req->app

body

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

$req->body['name']
// => "Dimitar"

cookies

An associative array of variables passed to the current script via HTTP Cookies.

$req->cookies['name']
// => "Dimitar"

files

An associative array of items uploaded to the current script via the HTTP POST method.

$req->files['avatar']
/* => Array
(
    [name] => avatar.png
    [type] => image/png
    [size] => 15476
    [tmp_name] => /tmp/phpn3FmFr
    [error] => 0
) */

hostname

Contents of the Host: header from the current request, if there is one.

$req->hostname
// => "example.com"

ip

The IP address from which the user is viewing the current page.

$req->ip
// => "127.0.0.1"

method

Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT', etc.

$req->method
// => "GET"

originalUrl

The URI which was given in order to access this page.

$req->originalUrl
// => "/search?q=something"

path

Contains the path part of the request URL.

$req->path
// => "/search"

port

The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.

$req->port
// => "80"

protocol

Name and revision of the information protocol via which the page was requested.

$req->protocol
// => "HTTP/1.1"

route

Contains the currently-matched route, a string. For example:

$req->route
// => "/"

query

An associative array of variables passed to the current script via the URL parameters.

$req->query['q']
// => "something"

scheme

Name of the information protocol via which the page was requested.

$req->scheme
// => "http"

secure

A Boolean property that is true if a TLS connection is established.

$req->secure
// => true

session

An associative array containing session variables available to the current script.

$req->session['user']
// => "admin"

xhr

A Boolean property that is true if the request's X-Requested-With header field is "XMLHttpRequest", indicating that the request was issued by a client library such as jQuery.

$req->xhr
// => true

Methods

accept(string $mimeType)

Checks if the specified content type is acceptable, based on the request's Accept HTTP header field.

$req->accept('application/json');
// => true

acceptEncoding(string $encoding)

Checks if the specified encoding is acceptable, based on the request's Accept-Encoding HTTP header field.

$req->acceptEncoding('gzip');
// => true

acceptLanguage(string $language)

Checks if the specified language is acceptable, based on the request's Accept-Language HTTP header field.

$req->acceptLanguage('en-US');
// => true

get(string $name)

Returns the specified HTTP request header field (case-insensitive match).

$req->get('Content-Type');

header(string $name)

Alias of get()

is(string $type)

Returns the matching content type if the incoming request's "Content-Type" HTTP header field matches the MIME type specified by the type parameter.

$req->is('html');

Response

append(string $field, $value)

Appends the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value. The value parameter can be a string or an array.

$res->append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
$res->append('Warning', '199 Miscellaneous warning');

attachment([string $filename=null])

Sets the HTTP response Content-Disposition header field to "attachment".

$res->attachment();
// Content-Disposition: attachment
$res->attachment('path/to/logo.png');
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png

clearCookie(string $name [, array $options=array()])

Clears the cookie specified by name.

$res->cookie('name', 'Dimitar', array('path' => '/admin'));
$res->clearCookie('name', array('path' => '/admin'));

contentType(string $type [, bool $fallback=false])

Alias of type()

Sets cookie name to value. The value parameter may be a string or array converted to JSON.

$res->cookie('name', 'Dimitar', array('domain' => '.example.com', 'path' => '/admin', 'secure' => true));
$res->cookie('rememberme', '1', array('expires' => time()+60*60*24*30, 'httpOnly' => true));

download(string $path[, string $filename = NULL])

Transfers the file at path as an "attachment". Typically, browsers will prompt the user for download.

$res->download('/report-12345.pdf');
$res->download('/report-12345.pdf', 'report.pdf');

end([string $data = NULL])

Ends the response process. Use to quickly end the response without any data.

$res->end();
$res->status(404)->end();

get(string $field)

Returns the HTTP response header specified by field. The match is case-insensitive.

$res->get('Content-Type');
// => "text/plain"

getHeaders()

Return an array with response headers.

$res->getHeaders();
/* => Array
(
    [X-Frame-Options] => sameorigin
    [X-XSS-Protection] => 1; mode=block
    [Connection] => keep-alive
) */

header(string $field, $value)

Alias of set()

json($body [, int $flags = 0])

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using json_encode().

$res->json(null);
$res->json(array('user' => 'Dimitar'));
$res->json(array('user' => 'Dimitar'), JSON_PRETTY_PRINT);
$res->status(500)->json(array('error' => 'message'));

location(string $path)

Sets the response Location HTTP header to the specified path parameter.

$res->location('/foo/bar');
$res->location('http://example.com');
$res->location('back');

redirect(string $path [, int $status = 302])

Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code.

$res->redirect('/foo/bar');
$res->redirect('http://example.com', 301);

render(string $view [, array $locals = array()])

Renders a view and sends the rendered HTML string to the client.

$res->render('index');

send($body)

Sends the HTTP response.

$res->send(array('some' => 'json'));
$res->send('<p>some html</p>');
$res->status(404)->send('Sorry, we cannot find that!');
$res->status(500)->send(array('error' => 'something blew up'));

sendStatus(int $code)

Sets the response HTTP status code to statusCode and send its string representation as the response body.

$res->sendStatus(200); // equivalent to $res->status(200)->send('OK')
$res->sendStatus(403); // equivalent to $res->status(403)->send('Forbidden')
$res->sendStatus(404); // equivalent to $res->status(404)->send('Not Found')
$res->sendStatus(500); // equivalent to $res->status(500)->send('Internal Server Error')

set($field [, $value])

Sets the response's HTTP header field to value. To set multiple fields at once, pass an array as the parameter.

$app->get('/readme.txt', function ($req, $res) {
    $res->set('Content-Type', 'text/plain');
    $res->set(array(
        'X-XSS-Protection' => '1; mode=block',
        'Connection' => 'keep-alive',
    ));
});

status(int $code)

Sets the HTTP status for the response.

$res->status(403)->end();
$res->status(400)->send('Bad Request');

type(string $value [, bool $fallback=false])

Sets the Content-Type HTTP header to the MIME type as determined by mimeLookup() for the specified type.

$res->type('html');               // => 'text/html'
$res->type('text');               // => 'text/plain'
$res->type('json');               // => 'application/json'
$res->type('application/json');   // => 'application/json'
$res->type('png');                // => 'image/png'
$res->type('unknown', true);      // => 'application/octet-stream'

vary(string $value)

Adds the field to the Vary response header, if it is not there already.

$res->vary('User-Agent')->render('docs');

Router

A router object is an isolated instance of middleware and routes. You can think of it as a "mini-application," capable only of performing middleware and routing functions. Every php-express application has a built-in app router.

$router = new \Riverside\Express\Router();

delete(string $path, $callback)

Routes HTTP DELETE requests to the specified path with the specified callback function.

$router->delete('/', function($req, $res){
    $res->json(array('status' => 'OK'));
});

get(string $path, $callback)

Routes HTTP GET requests to the specified path with the specified callback function.

$router->get('/', function($req, $res){
    $res->send('hello world');
});

head(string $path, $callback)

Routes HTTP HEAD requests to the specified path with the specified callback function.

$router->head('/', function($req, $res){
    $res->status(401)->end();
});

options(string $path, $callback)

Routes HTTP OPTIONS requests to the specified path with the specified callback function.

$router->options('/', function($req, $res){
    $res->json(array('status' => 'OK'));
});

param($name [, $regex = null])

Add custom parameters to use in a route path.

$router->param('uuid', '[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}');

// Then use in route path
$router->get('ticket/:uuid/', function($req, $res) {
    echo $req->params['uuid'];
});

patch(string $path, $callback)

Routes HTTP PATCH requests to the specified path with the specified callback function.

$router->patch('/', function($req, $res){
    $res->json(array('status' => 'OK'));
});

post(string $path, $callback)

Routes HTTP POST requests to the specified path with the specified callback function.

$router->post('/', function($req, $res){
    $res->json(array('status' => 'OK'));
});

put(string $path, $callback)

Routes HTTP PUT requests to the specified path with the specified callback function.

$router->put('/', function($req, $res){
    $res->json(array('status' => 'OK'));
});

route(string $path)

Returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use $router->route() to avoid duplicate route naming and thus typing errors.

$router->route('/invoices')
->get(function ($req, $res) {
    $res->render('invoices');
})
->post(function ($req, $res) {
    $res->json(array('status' => 'OK'));
});

run()

Run the application.

$router->run();