Skip to content

Databases

Using The Slim PHP Framework for Developing REST APIs

There’s a neat little framework for Ruby called Sinatra that makes it simple to configure REST-style API endpoints with just a smidgen of glue code. But why, asked PHP developer Josh Lockhart, should Ruby devs have all the fun?

Josh has been busy these past few months creating his own PHP-based REST DSL (Domain-Specific Language) called Slim. Slim has a minimal code footprint (hence its name), is easy to configure, and simple to use. With just a touch of additional code, you can wire up your existing PHP functions to return data in response to a URL request. In this post, I’ll demonstrate how to install and configure Slim, create an endpoint that performs a SELECT against an arbitrary MySQL table, and return the result in JSON format.

Installing Slim

Installation is easy: unpack the Slim ZIP or Gunzip file into either the root directory of your Web site, or into a subdirectory. For this post, I’ll be installing Slim into the directory /services, off of the Apache document root.

How Slim Works

Let’s take a quick look at the directory structure of Slim:

Slim operates by re-routing the path portion of URL requests to a file named bootstrap.php, which initializes Slim. It’s also the file in which you define your own endpoints, which are called routes. A route is a URL path defined relative to the Slim base directory. Assuming that Slim is installed in http://localhost/services/, http://localhost/services/foo and http://localhost/services/bar define two distinct routes named foo and bar.

You can define new routes by defining a routing function in bootstrap.php. The .htaccess file contains a set of mod_rewrite rules that read the route from the URL, and supply it as an argument to bootstrap.php. This triggers your custom routing function.

Enabling mod_rewrite

If you haven’t enabled mod_rewrite in your Apache server, you will need to¬†uncomment the following line from your httpd.conf file:

LoadModule rewrite_module modules/mod_rewrite.so

In order for .htaccess to work, you may also need to change the value of the AllowOverride directive in httpd.conf from None to All.

Currently, the Slim .htaccess code looks like this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ bootstrap.php [QSA,L]

You will want to add one more line to this above the current RewriteCond
line if you want to access any subdirectory below the Slim installation directory:

RewriteCond %{REQUEST_FILENAME} !-d

Defining Your PHP Code

The following simple PHP code defines a class that performs a SELECT against an arbitrary table in the Northwind database. This code can (and should) be defined in a separate file from bootstrap.php; I’ll show how to wire the two together in the next section.

class Northwind {
	private $db = "127.0.0.1";
	private $user="root";
	private $pass = "";

	function __construct() {}

	function getTable($name) {
		$dbconn = mysql_connect($this->db, $this->user, $this->pass);
		if (!$dbconn) {
			throw new Exception("Cannot connect to database.");
		}

		mysql_select_db("northwind", $dbconn);

		$sql = "SELECT * FROM " . mysql_real_escape_string($name, $dbconn);
		$query_result = mysql_query($sql, $dbconn);
		if (!$query_result){
			throw new Exception("Invalid query. Error: " . mysql_error());
		}

		$rows = array();
		while ($row = mysql_fetch_assoc($query_result)) {
			array_push($rows, $row);
		}

		return $rows;
	}
}

Defining Your Slim Route

Let’s crack open bootstrap.php, and look at how a route is defined. This core slim file contains a couple of sample routes, such as:

Slim::get('/hello/:name', function ($name) {
	echo "<p>Hello, $name!</p>";
	echo "<p>This route using name "Bob" instead of "$name" would be: "
. Slim::urlFor('hello', array('name' => 'Bob')) . '</p>';
})->name('hello')->conditions(array('name' => 'w+'));

If you have Slim installed on a local Apache installation, you can test this route by invoking the URL http://localhost/services/hello/Jay.

Slim::get defines a new Slim route that is invoked as an HTTP GET request. The first argument is the route itself. Any part of the route preceded by a colon is a variable argument, and what follows the colon is a pattern-matching token. (We’ll call these route parameters, to distinguish them from query string and form parameters.)

The second argument is an anonymous function. Anonymous functions are supported in PHP 5.3 and greater; you can use Slim without them, but they make life easier. This function simply prints out a message that includes the route parameter name.

The call to the conditions() method at the end of this code block defines the pattern for the route parameter. It also gives our route a convenient name so that we can retrieve and modify its definition in Slim.

Adding a route that calls our Northwind class is fairly straightforward. First, we require the file containing our class:

require_once('../northwind.php');

Slim defines two functions, named Slim::before() and Slim::after(), that are called before and after each route is executed. We need to comment out the code that’s currently in these methods before we proceed.

Slim::before(function () {
	//Slim::response()->write('<p>Before!</p>');
});

Slim::after(function () {
	//Slim::response()->write('<p>After!</p>');
});

Finally, we define our route. We will define our route so that it has one route parameter: the name of the table we want to query.

Slim::get('/northwind/:name', function ($tablename) {
	$nw = new Northwind();

	$result = $nw->getTable($tablename);

	header("Content-Type: application/json");
	echo json_encode($result);
})->name('northwind')->conditions(array('tablename' => 'w+'));

And that’s it. If you have Microsoft’s Northwind database imported into your MySQL installation, calling http://localhost/services/northwind/employees will return all data from the employees table in JSON format.

Much More

There are far more features to Slim than I’ve covered here. For example, you can call Slim::request() to obtain a request object that grants you access to query string and form parameters, among other data. Slim also supports pass-through pattern-matching, route redirection, custom error and 404 responses, and more. Give it a whirl, and see what you can do with the power of Sinatra-style routing in PHP.

Be Sociable, Share!
    The following two tabs change content below.

    Add Your Comment (Get a Gravatar)