Routing

REST is an architectural style that allows interaction over HTTP of loosely coupled application resources. Resources are described by using a uniform resource name (or URN) at your API endpoint (URL).

As detailed previously each @Drest\Route must be accompanied with a routePattern to be used for matching client requests, a name, and a set of matching verbs. When the drest manager object is constructed your route patterns are read and registered onto a router (Note: you must use caching in production to drastically reduce the cost of this operation).

When dispatch() is called a lookup is performed on all registered routes (include a verb check). If a single route is matched, then this is used. If multiple routes are matched, then an exception is thrown.

As each route has a unique name which you’re able to bypass the routing mechanism with by passing it into a dispatch call. This should be the full classname (namespace included if applicable) of the entity class and the route name separated by double colon ( :: ). For example:

// dispatch a specific route, bypassing the router lookup.
$drestManager->dispatch(null, null, 'Entities\User::get_user');

Parameters

You can add parameters to your routePattern definition by using a colon ( : ) followed by the variable name. Here are some examples:

routePattern="/user/:id" 
routePattern="/users/:status"

If a match is made on these routes then the parameters interpreted from the URN are available via a Drest\Request::getRouteParam($name) call. You can access these from a custom service action like so:

// get an array of all
$this->service->getRequest()->getRouteParam();
// get just the 'status' parameter
$this->service->getRequest()->getRouteParam('status');

Note on the default [GET] service actions, any parameter defined in the route will be used as a filter.

Wildcarding

Parameters can optionally be used with a wildcard to allow you to match a route that has a number of URN parts. The wildcard character is a plus sign (+) which should be used at the end of a parameter declaration like so:

// this will match the path "/users/active/with/other/parts"
routePattern="/users/:status+"

echo $this->service->getRequest()->getRouteParam('status');
// active/with/other/parts

Additional Conditionals

Along with matching the route path you can also specify a conditional regular expression for each route parameter to meet. If a condition is not met with the URN then the the route is not deemed a match.

For example you may want to insure an :id parameter doesn’t match URNs such as /user/billy by adding a condition that ensures its a decimal.

@Drest\Route(
    name="get_user",
    routePattern="/user/:id",
    routeConditions={"id": "\d+"},
    verbs={"GET"}
 )

Or that the a :year parameter is of a valid format

@Drest\Route(
    name="get_applicants",
    routePattern="/applicants/:year",
    routeConditions={"year": "(19|20)\d\d"},
    verbs={"GET"}
 )