PHP Routers for Creating REST APIs

My primary programming project is the game I am creating with my friends Jeff and Jesse. But I also have to work on other projects to make a living because our game will make us no money until its completion. Some of those recent side-projects involve building PHP applications based around REST APIs. So today I want to talk about some third-party libraries and packages I have examined for use in such projects.

What I Mean by ‘Router’

When I say ‘router’ in this article I am referring to a library or framework which allows me to define the behavior of my program in terms of URL routes. For example, if my application has a /users/ part of its URL then the router lets me describe how the program responds to various HTTP methods on that URL. They help me program logic for scenarios where the program receives a GET request on that URL, or a DELETE request, or any of the other HTTP methods.

Below are some of the routers I have used and experimented with.

Laravel

Laravel is the most well-documented router I have seen. The site even brags about this, but it’s justified bragging in my opinion. Like most routers, Laravel works by allowing you to define behavior for HTTP methods on specific URLs or URL patterns. For example:

/**
 * Return a user with the given ID.
 */
Route::get("/user/(:num)/", function ($id)
           {
                   /* Create a User object with that $id and then
                    * build a view from that to show his or her
                    * information.
                    */
           });

/**
 * Update the information for an existing user.  We assume the PUT
 * request contains the new information in a JSON format that we
 * document elsewhere.
 */
Route::put("/user/(:num)/", function ($id)
           {
                   $data = Input::json();

                   /* Fetch a User like we do with GET but then pass
                    * $data to a method on that class that takes the
                    * JSON and updates the appropriate values,
                    * probably saving the User to a database after
                    * that finishes.
                    */
           });

You can see how Laravel lets you capture parts of URLs and pass those to the functions for handling those requests, such as how the example above grabs user ID numbers.

Of the routers I mention in this article, Laravel takes the most effort to setup. But it also provides the most features with controllers, views, everything you need for the classic MVC design.

Klein.php

Klein.php is easier to setup and use than Laravel but provides less features. However, it still packs enough functionality to be quite useful. Like other routers it lets you define the behavior of HTTP methods on various URLs, also allowing you to capture parts of them like Laravel, with some degree of validation to boot. But one nice, stand-out feature of Klein.php is creating ‘route namespaces’. These allow you to group the behavior of a URL and its sub-components in a nice fashion. Here is the example from the official site:

with('/users', function () {

    respond('GET', '/?', function ($request, $response) {
        // Show all users
    });

    respond('GET', '/[:id]', function ($request, $response) {
        // Show a single user
    });

});

The way Klein.php lets you group URLs like this creates a nice organization in the code. It is my favorite aspect of the library.

Respect\Rest

Respect is the library I have used most recently. I am enjoying it because it is thin, easy to incorporate into applications, and efficient at what it does. It has a lot of the features of the previously mentioned libraries, such as capturing parameters from URLs. But one cool feature of Respectis how it allows you to create classes that handle HTTP methods, and then bind those to URLs like so:

use Respect\Rest\Routable;

class MyArticle implements Routable {
    public function get($id) { }
    public function delete($id) { }
    public function put($id) { }
}

$r3->any('/article/*', 'MyArticle');

The framework also provides some nice support for streaming content and basic authentication, the latter often being useful for handling PUT and POST requests that modify data.

Conclusion

If you are writing a PHP application that defines a REST-based API then I suggest you consider each of these frameworks. They have their pros and cons, and I certainly have not listed them in depth in this article. But I hope my skimming of the surface at least piques your interest in their capabilities. Try them out and find which one works best for you.

Advertisements

One thought on “PHP Routers for Creating REST APIs

Add Your Thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s