Make great applications with PHP

simply put: Routing - All about base URLs, internal URIs, modules and actions

Your app on the web

Your APP_DIR/web folder contains an .htaccess file that instructs Apache and Litespeed servers to use URL rewriting. For other browsers, you will have to do something similar. Regular files like images, css etc. are handled by the web server as expected, e.g.
If URL rewriting is on, then your app's URL will look like this:
But if it's not on, then your app's URLs will mostly look like this:

In PIE, when a request comes in for a URL like
we would refer to
  • as the "base url",
  • as the "controller URL", and
  • foo/bar/baz as the "tail".

Routing to an internal URI

Let's now customize the routes used to channel web requests into actions we will create for our app. When a request comes in to the webserver, the Pie_Dispatcher uses the routes to translate the requested URL into an internal URI, which is basically an object $uri that contains at least the fields $uri->action and $uri->module.

In your PHP code, you can access this information as follows:

// returns the requested URL:
$url = Pie_Request::url();

// returns the base URL of your app, parent of the /css and other paths
$base_url = Pie_Request::baseUrl();

// return value may end with "/index.php" depending on the web request
$controller_url = Pie_Request::baseUrl(true);

// returns the $uri object obtained from routing the URL
$uri = Pie_Dispatcher::uri();

Take a look at your APP_DIR/config/app.json file. The pie/routes config field specifies the routes using an associative array. The keys of the array are patterns against which PIE tries to match the tail of the requested URL. The process is as follows:

  • The tail (e.g. foo/bar/baz) is split into segments by '/' (slashes)
  • The routes are examined in the order they appear, until a matching route is found.
  • A route matches if its pattern contains matching literal values (foo, bar) in the right places,
  • The pattern may also have variables that can match any wildcard. For example, the pattern "foo/$action/baz" matches the tail "foo/bar/baz" and sets the $uri->action field to "bar".
  • Some segments can be of the form $variable.literal, which would match "anything.literal". This is useful to mimic files ending in .html, etc. by having patterns such as "$module/$action.html"
  • If the value of the route is null, this route is skipped in the matching.
  • If a match is found, then the value of the route is examined. If it is an associative array, then it is merged into the $uri. This is typically used for setting fields (such as $uri->module) that have not been specified by the pattern.
  • If a match is not found, an empty URI is returned.
  • By convention, routing is considered successful only if at least $uri->module and $uri->action have been set at the end of it.

Complete reference to PHP ON PIE

TODO: include an iframe with PHPDoc-generated reference