Table of Contents
Routing is the machinery that takes a requested URL path like
/product/23 and ‘routes’ or dispatches control to a
specific point in your application. In most frameworks, including
Recess, this is to a method in a Controller.
Using a framework that has fast, flexible, RESTful routing is important
because URLs are fundamental to how people, search engines, and web
services interact with you web application.
Let’s dive right into some code and take a look at how we can set up a route to a method in a controller:
Example 8.1. A simple GET route.
<?php TestController extends Controller { /** !Route GET, /hello/world */ function aMethod() { echo 'Hello PHP Community!'; exit; } }
What’s that funny stuff above the function? It’s a Recess
RouteAnnotation. Recess annotations may look a
bit strange but they’re really simple. They are written inside of
doccomments, a language construct in PHP which begins
with a forward slash and two asterisks. Recess annotations are banging.
Literally, they start with an exclamation point, or, BANG! (as opposed
to the @-symbol if you’re used to Java style annotations). The Route
annotation has two parameters. The first is the HTTP method such as
GET, POST, PUT,
or DELETE and the second is the URL path.
When a part of the route is preceded with a dollar sign it becomes a method parameter. Here is an example:
Example 8.2. Simple parametric routes using route $parameters
<?php class TestController extends Controller { /** !Route GET, /hello/$first/$last */ function aMethod($first, $last) { echo "Hello $first $last!"; exit; } }
Now if we browse to /hello/PHP/Community the
browser will print “Hello PHP Community”. Parametric routes are often
used with ID or primary key columns in a database. For example, if I
were building a store in Recess I might have a Product Details page that
used a route like: !Route GET, /product/$id
Controller methods can have multiple routes. For example, we can combine the previous two methods into one:
Example 8.3. Multiple routes on a single controller method
<?php class TestController extends Controller { /** * !Route GET, /hello/world * !Route GET, /hello/$first/$last * */ function aMethod($first = "PHP", $last = "Community") { echo "Hello $first $last!"; exit; } }
If you accidentally add a route that conflicts with another somewhere else in your app Recess will tell you where the conflict occurred. The Recess Diagnostics error screen shows you where in your code the conflict occurred.
If you’re familiar with Cake or Rails you may be wondering what is the upside to specifying routes in-line with my methods? The long and short of it is, it is more DRY. With a separate routes file you must duplicate the name of a controller and method which a route maps to. So if you refactor your controller code you must remember to go and update your routes file as well. By keeping the two together it’s never a mystery what URL will take you to the controller method you’re working on.