News Archive
PhpRiot Newsletter
Your Email Address:

More information

Building A RESTful PHP Server: Routing the Request

Note: This article was originally published at Planet PHP on 23 January 2012.
Planet PHP

This is the second part of a series, showing how you might write a RESTful API using PHP. This part covers the routing, autoloading, and controller code for the service, and follows on from the first installment which showed how to parse the incoming request to get all the information you need.

Routing to Controllers

In this setup, we'll have models, controllers and ... output handlers. It's not really a view, because all we will do is transform the data to a given output format. More on that later on - for now we will return the data we fetch in the controller back to index.php, and dump it out so we can inspect it.

For RESTful routing, each thing in the system is considered as a resource, and it has a unique resource identifier (or URI) to represent it. In this example system, we have users and groups. Each resource belongs to a collection, which is the level above the resource - I usually think of files being in directories when I think of resources belonging to collections.

So for an incoming GET request to /users, we will return a list of users as this is the collection. Within our application, this means calling the getAction() on the UsersController, so index.php now looks like this:

// route the request to the right place $controller_name = ucfirst($url_elements[1]) . 'Controller'; if (class_exists($controller_name)) { $controller = new $controller_name(); $action_name = strtolower($verb) . 'Action'; $result = $controller-$action_name(); print_r($result); }

At this point, you'll write a controller and model that will look hauntingly familiar from all the other MVC systems you've ever written! Before we do that though, let's talk about architecture and autoloading.

Designing and Loading Classes

Working with classes gets much easier if you put them in reliable places and call them reliable names. If you do, you can autoload them and avoid all those tedious require() statements. My directory structure looks like this:

. a"oa"a" controllers a"AA a"oa"a" MyController.php a"AA a""a"a" UsersController.php a"oa"a" index.php a""a"a" models

The users controller is in the controllers directory, and it inherits from a shared parent controller called MyController. I have no idea what will go into here, but from experience, I recommend that both models and controllers should inherit from a shared parent - as will our output handlers (because we don't have views) later on. You can see that the controllers are reliably found in the controllers directory, called something ending in *Controller.php. This makes it simple to add to an autoload rule

Truncated by Planet PHP, read more at the original (another 12049 bytes)