| Building A RESTful PHP Server: Routing the Request |
| Monday, 23 January 2012 03:06 |
|
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 ControllersIn 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 // 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 ClassesWorking 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 . ├── controllers │ ├── MyController.php │ └── UsersController.php ├── index.php └── models The users controller is in the Truncated by Planet PHP, read more at the original (another 12049 bytes) read original article |
