Stud.IP  5.4
RouteMap Class Reference
Inheritance diagram for RouteMap:
Activity Blubber Clipboard Contacts Course Discovery Events Feedback FileSystem Forum Messages News ResourceBooking ResourceCategories ResourcePermissions ResourceProperties ResourceRequest Resources RoomClipboard Schedule Semester Studip User UserConfig Wiki

Public Member Functions

 __construct ()
 init ($router, $route)
 paginated ($data, $total, $uri_params=[], $query_params=[])
 paginate ($uri_format, $total, $offset=null, $limit=null)
 collect ($data)
 status ($status)
 headers ($headers=[])
 body ($body)
 contentType ($mime_type, $params=[])
 error ($status, $body=null)
 etag ($value, $strong_etag=true, $new_resource=null)
 expires ($amount, $cache_control=[])
 cacheControl ($values)
 halt ()
 lastModified ($time)
 notFound ($body=null)
 redirect ($url, $args=null)
 sendFile ($_path, $opts=[])
 url ($addr, $url_params=null)
 urlf ($addr_f, $format_params, $url_params=null)
 getRoutes ($http_method=null)
 getResponse ()

Protected Member Functions

 extractConditions ($docblock, $conditions=[])

Protected Attributes

 $data = null
 $pagination = false

Detailed Description

RouteMaps define and group routes to resources.

Instances of RouteMaps are registered with the RESTAPI to participate in the routing business.

A RouteMap defines at least one handler method which has to be annotated with one of these annotations correlating to HTTP request methods:

/ * *
* An example handler method
* @get /foo
* @post /bar/:id
* @put /baz/:id/:other_id
* @delete /
* /
public function anyMethodName($id, $other_id = null) {}

By default, all API routes are unaccessible for nobody users. To explicitly allow access for nobody users, add the allow_nobody tag to the handler method's doc block. Example:

/ * *
* Another example handler method
* @get /foo
* @allow_nobody
* /

As soon as the Router matches a HTTP request to a handler defined in a RouteMap, it calls RouteMap::init to initialize it and especially the instance field $this->response of type RESTAPI. You do not call RouteMap::init on your own.

After the router has initialized this RouteMap, the router tries to call a method before of this signature:

public function before(Router $router, Array $handler, Array $parameters);

The parameter $handler is a callable (as in function is_callable) consisting of the instance of this RouteMap and the name of a method of this instance. You may change the values of this array to redirect to another handler.

The parameter $parameters is an associative array whose keys correlate to the placeholders in the matched URI template. The values are the actual values of that placeholders in regard to the HTTP request.

After calling RouteMap::before control is transfered to the actual handler method. The values of the placeholders in the URI template of the annotation are send as arguments to the handler.

Example: We have got this handler method defined:

/ * *
* @get /foo/:id/bar/:other_id
* /
public function fooHandler($id, $other_id) {

The router receives a request like this: http://[..]/foo/1/bar/2 and matches it to our fooHandler which is then called something like that:

$result = $routeMap->fooHandler(1, 2);

In your handler methods you have to process the input and return some output data, which is then rendered in an appropriate way after negotiating the content format in the Router.

Thus the return value of your handler method becomes the body of the HTTP response.

The RouteMap class defines several methods to ease up your work with the HTTP specifica.

The methods RouteMap::status, RouteMap::headers and RouteMap::body correlate to the components of a HTTP response.

There are helpers for returning paginated collections, see RouteMap::paginated.

If you encounter an error or have to stop further processing, see methods RouteMap::halt, RouteMap::error and RouteMap::notFound.

These methods are DISRUPTIVE as they immediately stop the control flow in your handler:

public function fooHandler($id)
// do something
// this line will never be reached

If you want to simply send a redirection response (HTTP status code of 302 or 303), you may find calling RouteMap::redirect helpful.

To generate a URL to a handler, use RouteMap::url

When you find the need to return the content of a file, please see RouteMap::sendFile which will help you with streaming it to the client. For custom streaming just return a Closure from your handler method.

There are several other methods which you may find useful each matching a HTTP header:

You can access the data sent in the body of the current HTTP request using the $this->data instance variable.

  • If the request was of Content-Type application/json, the body of the request is decoded using json_decode.
  • If the request was of Content-Type application/x-www-form-urlencoded, the body of the request is decoded using parse_str.
  • Otherwise the request will not be parsed and $this->data will just contain the raw string.

NOTE: The result of the described parsing will always contain strings encoded in windows-1252. If the original body was UTF-8 encoded, it is automatically re-encoded to windows-1252.

Jan-Hendrik Willms
mlunz.nosp@m.ena@.nosp@m.uos.d.nosp@m.e GPL 2 or later
Stud.IP 3.0

Constructor & Destructor Documentation

◆ __construct()

__construct ( )

Constructor of the route map. Initializes neccessary offset and limit parameters for pagination.

Member Function Documentation

◆ body()

body (   $body)

Set the HTTP body of the current response.

string$bodythe body to send back

◆ cacheControl()

cacheControl (   $values)

This sets the Cache-Control header of the HTTP response.


$this->cacheControl(array('public', 'must-revalidate'));
array$valuesan array containing Cache-Control directives.

◆ collect()

collect (   $data)

Low level method for paginating collections. You better use RouteMap::paginated instead of this.

Adjusts the result set to return a collection. A collection consists of the passed data array and the associated pagination information if available.

Be aware that the passed data has to be already sliced according to the pagination information.

array$dataActual dataset
array Collection "object"

◆ contentType()

contentType (   $mime_type,
  $params = [] 

Set the Content-Type of the HTTP response given a mime type and optionally further parameters as discusses in RFC 2616 14.17.

If no charset is given, it defaults to Stud.IP's 'windows-1252'.


// results in "Content-Type: image/gif"
// results in "Content-Type: text/html;charset=ISO-8859-4"
// results in "Content-Type: text/html;charset=ISO-8859-4"
$this->contentType('text/html', array('charset' => 'ISO-8859-4'));
// results in "Content-type: multipart/byteranges; boundary=THIS_STRING_SEPARATES"
$this->contentType('multipart/byteranges', array('boundary' => 'THIS_STRING_SEPARATES'));
string$mime_typea string describing a MIME type like 'application/json'
array$paramsoptional parameters as described above

◆ error()

error (   $status,
  $body = null 

(Nice) sugar for calling RouteMap::halt and therefore as DISRUPTIVE. Code after calling RouteMap::error will not be evaluated.

See also
integer$statusa number indicating the HTTP status code; probably something 4xx or 5xx-ish
string$bodyoptional; the body of the HTTP response

◆ etag()

etag (   $value,
  $strong_etag = true,
  $new_resource = null 

Sets the HTTP response's Etag header and halts, if the incoming HTTP request was a matching conditional GET using an 'If-None-Match' header. Thus it is a possibly DISRUPTIVE method as it will stop evaluation in that case and send a '304 Not Modified'.

Detail: If the request contains an If-Match or If-None-Match header set to *, a RouteMap assumes a match on safe (e.g. GET) and idempotent (e.g. PUT) requests. (In those cases it thinks that the resource already exists and therefore matches a wildcard.). This can be changed by passing an appropriate value for the $new_resource parameter.

Details of this can be found in RFC 2616 14.24 and 14.26

string$valuean identifier uniquely identifying the current state of a resource
bool$strong_etagoptional; indicates whether the etag is a weak or strong (which is the default) cache validator. Have a look at the RFC for details.
bool$new_resourceoptional; a way to tell the RouteMap that this is a new or existing resource. See above.

◆ expires()

expires (   $amount,
  $cache_control = [] 

This sets the Expires header and the Cache-Control directive max-age.

Amount is an integer number of seconds in the future indicating when the response should be considered "stale". The $cache_control parameter is passed to RouteMap::cacheControl along with the automatically generated max_age directive.

int$amountan integer specifying the number of seconds this resource will go stale.
array$cache_controloptional; more directives for RouteMap::cacheControl which is always automatically called using the computed max_age

◆ extractConditions()

extractConditions (   $docblock,
  $conditions = [] 

Extracts defined conditions from a given docblock.

Docblock$docblockDocBlock to examine
array$conditionsOptional array of already defined conditions to extend
array of all extracted conditions with the variable name as key and pattern to match as value

◆ getResponse()

getResponse ( )

Returns the response object


◆ getRoutes()

getRoutes (   $http_method = null)

Returns a list of all the routes this routemap provides.

string$http_methodReturn only the routes for this specific http method (optional)
array of all routes grouped by method

◆ halt()

halt ( )

This very important method stops further execution of your code. You may specify a status code, headers and the body of the resulting response. As the name implies, this method is DISRUPTIVE and will not return.

// stops any further code of a route
// you may specify an HTTP status
// you may specify the HTTP response's body
$this->halt('my ethereal body')
// or even both
$this->halt(100, 'Yes, pleazze!')
// giving headers
$this->halt(417, array('Content-Type' => 'x-not-a-cat'), 'Cats only!')

This method is called by every single DISRUPTIVE method.

integer$statusoptional; the response's status code
array$headersoptional; (additional) header lines which get merged with already set headers
string$bodyoptional; the response's body

◆ headers()

headers (   $headers = [])

Set multiple response headers of the current response by merging them with already set ones.

$routemap->headers(array('X-example' => "yep"));
array$headersthe headers to set
array the headers of the current response

◆ init()

init (   $router,

Initializes the route map by binding it to a router and passing in the current route.

Router$routerRouter to bind this route map to
array$routeThe matched route out of Router::matchRoute; an array with keys 'handler', 'conditions' and 'source'

◆ lastModified()

lastModified (   $time)

This method sets the Last-Modified header of the HTTP response and halts on matching conditional GET requests. Thus this method is DISRUPTIVE in certain circumstances.

You have to give an integer typed timestamp (in seconds since epoch) to specify the data of the last modification to the requested resource.

If the current HTTP request contains an If-Modified-Since header, its value is compared to the specified $time parameter. Unless the header's value is sooner than the given $time, further execution is precluded and the RouteMap returns with a '304 Not Modified'.

integer$timea timestamp described in seconds since epoch

◆ notFound()

notFound (   $body = null)

Halts execution and returns a '404 Not Found' response.

Sugar for calling RouteMap::error(404) and therefore DISRUPTIVE. Code after calling RouteMap::notFound will not be evaluated.

See also
string$bodyoptional; the body of the HTTP response

◆ paginate()

paginate (   $uri_format,
  $offset = null,
  $limit = null 

Low level method for paginating collections. You better use RouteMap::paginated instead of this.

Set the pagination data used by the RouteMap::collect.

Routemap Returns instance of self to allow chaining

◆ paginated()

paginated (   $data,
  $uri_params = [],
  $query_params = [] 

Marks this chunk of data as a slice of a larger data set with a sum of "total" entries.

mixed$dataChunk of data (should be sliced according to current offset and limit parameters).
int$totalThe total number of data entries in the according set.
array$uri_paramsNeccessary parameters when generating uris for the current route.
array$query_paramsOptional query parameters.

◆ redirect()

redirect (   $url,
  $args = null 

Stops your code and redirects to the URL provided. This method is DISRUPTIVE like RouteMap::halt

In addition to the URL you may provide the status code, (additional) headers and a request body as you would when calling RouteMap::halt.

$this->redirect('/foo', 201, array('X-Some-Header' => 1234), 'and even a body');
See also
string$urlthe URL to redirect to; it will be filtered using RouteMap::url, so you may call it with those nice and small strings used in the annotations
mixed$argsoptional; any combinations of the three parameters as in RouteMap::halt

◆ sendFile()

sendFile (   $_path,
  $opts = [] 

Stops execution of your code and starts sending the specified file. This method is DISRUPTIVE.

Using the $opts parameter you may specify the file's mime content type, sending an appropriate 'Content-Type' header, and you may specify the 'Content-Disposition' of the file transfer.


$this->sendFile('/tmp/c29tZSB0ZXh0', array(
'type' => 'image/png',
'disposition' => 'inline',
'filename' => 'cutecats.png'));
string$_paththe filesystem path to the file to send
array$optsoptional; specify the content type, disposition and filename

◆ status()

status (   $status)

Set the HTTP status of the current response.

integer$statusthe HTTP status of the response

◆ url()

url (   $addr,
  $url_params = null 

Generate a URL to a given handler using a URL fragment and URL parameters.


// result in something like "/some/path/api.php/course/123/members?status=student"
$this->url('course/123/members', array('status' => 'student'));
string$addra URL fragment to a handler
array$url_paramsoptional; URL parameters to add to the generated URL
string the resulting URL

◆ urlf()

urlf (   $addr_f,
  $url_params = null 

A vsprintf like variant to the RouteMap::url method.


// results in "[...]/api.php/foo/some_id?status=student"
$this->urlf("foo/%s", array("some_id"), array('status' => 'student'));
string$addr_fa URL fragment to a handler containing sprintf-ish format sequences
array$format_paramsvalues to fill into the format markers
array$url_paramsoptional; URL parameters to add to the generated URL
string the resulting URL

Field Documentation

◆ $data

$data = null

◆ $limit


The limit of a RouteMap::paginated collection as requested by the client.

◆ $offset


The offset into a RouteMap::paginated collection as requested by the client.

◆ $pagination

$pagination = false

Internal property which is used by RouteMap::paginated and contains everything about a paginated collection.

◆ $response


◆ $route


◆ $router


The documentation for this class was generated from the following file: