August 9, 2011

Really Easy RESTful Servers Using the Limonade Micro-framework

Looking for a quick and easy way to create a RESTful service in PHP, I set out looking for a good micro-framework to handle the RESTful service basics and allow me to focus on business logic. Having used Sinatra in the past, I knew a micro-framework would give me just enough MVC without a “bunch of cruft”. Enter Limonade. From their site:

Limonade is a PHP micro framework for rapid web development and prototyping.

The basics are this: you require the library, define a “dispatch”, and write your business logic. Say your want to provide a RESTful service that will provide CRUD operations for users in your system. Here is your shell:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
require_once 'vendors/limonade.php';

// Get a list of users
dispatch_get('/users', 'get_users');
function get_users() {
// Do something to get $users as an array of Users
return json(compact('users'));
}

// Get an individual user
dispatch_get('/users/:user_id', 'get_user');
function get_user() {
$user_id = params('user_id');
// Do something to get a user
return $list_of_users;
}

// Create a new user
dispatch_post('/users', 'create_user');
function create_user() {
// Do something to create a user
if ($success) {
status(201);
} else {
halt(422, 'Could not create user')
}
}

// Update an individual user
dispatch_put('/users/:user_id', 'update_user');
function update_user() {
$user_id = params('user_id');
// Do something to get a user
if ($success) {
status(201);
} else {
halt(422, 'Could not update user')
}
}

// Update an individual user
dispatch_delete('/users/:user_id', 'delete_user');
function update_user() {
$user_id = params('user_id');
// Do something to delete a user
if ($success) {
status(201);
} else {
halt(422, 'Could not update user')
}
}

run();

Some interesting “gotchas” we came across when implementing this:

  • Limonade can use named functions:
    1
    dispatch('/', 'hello_world');
  • static class method calls:
    1
    dispatch('/', array('MyClass', 'hello_world'));

    or:

    1
    dispatch('/', 'MyClass::hello_world');
  • object method calls
    1
    dispatch('/', array($my_obj, 'hello_world'));
  • but to use lambda functions:
    1
    dispatch('/', function() {return 'Hello World'; });

    you will need to be using PHP 5.3.0 or later.

  • You can do a lot of cool stuff by defining before(); and after(); methods. You can also confuse yourself (and others) when data is manipulated there.

One Response to Really Easy RESTful Servers Using the Limonade Micro-framework

  1. Pingback: orbiteleven.net » Really Easy RESTful Servers Using the Limonade Micro-framework