What is Bullet?

Bullet is a functional PHP micro-framework that helps you easily create REST APIs and web applications that automatically conform to the requirements of the HTTP specification. Bullet is resource and URI-oriented and comes pre-loaded with powerful HTTP features like content-negotiation and caching.

Requirements

  • PHP 5.3+ (PHP 5.4 recommended)
  • Composer for all package management and autoloading (may require command-line access)

Rules

  • Apps are built around HTTP URIs and defined paths, not forced MVC (but MVC-style code organization is still highly recommended and encouraged)
  • Bullet handles one segment of the path at a time, and executes the callback for that path segment before proceesing to the next segment (path callbacks are executed from left to right, until the entire path is consumed).
  • If the entire path cannot be consumed, a 404 error will be returned (path was not found).
  • If the path can be fully consumed, and HTTP method handlers are present in the path but none are matched, a 405 “Method Not Allowed” response will be returned (if the request is a POST, but you only have a GET handler).
  • If the path can be fully consumed, and format handlers are present in the path but none are matched, a 406 “Not Acceptable” response will be returned (if ‘xml’ is requested, but you only have a ‘json’ handler).

Advantages

  • Super flexible routing. Because of the way the routing callbacks are nested, Bullet’s routing system is one of the most flexible of any other PHP framework or library. You can build any URL you want and respond to any HTTP method on that URL. Routes are not restricted to specific patterns or URL formats, and do not require a controller with specific method names to respond to specific HTTP methods. You can nest routes as many levels deep as you want to expose nested resources like posts/42/comments/943/edit with a level of ease and elegance not found elsewhere.

  • Reduced code duplication (DRY). Bullet takes full advantage of its nested closure routing system to reduce a lot of typical code duplication required in most other frameworks. In a typical MVC framework controller, some code has to be duplicated across methods that perform CRUD operations to run ACL checks and load required resources like a Post object to view, edit or delete. With Bullet’s nested closure style, this code can be written just once in a path or param callback, and then you can use the loaded object in subsequent path, param, or HTTP method handlers. This eliminates the need for “before” hooks and filters, because you can just run the checks and load objects you need before you define other nested paths and use them when required.

Syntax

Bullet is not your typical PHP micro framework. Instead of defining a full path pattern or a typical URL route with a callback and parameters mapped to a REST method (GET, POST, etc.), Bullet parses only ONE URL segment at a time, and only has two methods for working with paths: path and param. As you may have guessed, path is for static path names like “blog” or “events” that won’t change, and param is for variable path segments that need to be captured and used, like “42” or “my-post-title”. You can then respond to paths using nested HTTP method callbacks that contain all the logic for the action you want to perform.

This type of unique callback nesting eliminates repetitive code for loading records, checking authentication, and performing other setup work found in typical MVC frameworks or other microframeworks where each callback or action is in a separate scope or class method.

$app = new Bullet\App(array(
    'template.cfg' => array('path' => __DIR__ . '/templates')
));
 
// 'blog' subdirectory
$app->path('blog', function($request) use($app) {
 
    $blog = somehowGetBlogMapper(); // Your ORM or other methods here
 
    // 'posts' subdirectory in 'blog' ('blog/posts')
    $app->path('posts', function() use($app, $blog) {
 
        // Load posts once for handling by GET/POST/DELETE below
        $posts = $blog->allPosts(); // Your ORM or other methods here
 
        // Handle GET on this path
        $app->get(function() use($posts) {
            // Display all $posts
            return $app->template('posts/index', compact('posts'));
        });
 
        // Handle POST on this path
        $app->post(function() use($posts) {
            // Create new post
            $post = new Post($request->post());
            $mapper->save($post);
            return $this->response($post->toJSON(), 201);
        });
 
        // Handle DELETE on this path
        $app->delete(function() use($posts) {
            // Delete entire posts collection
            $posts->deleteAll();
            return 200;
        });
 
    });
});
 
// Run the app and echo the response
echo $app->run("GET", "blog/posts");
 

Capturing Path Parameters

Perhaps the most compelling use of URL routing is to capture path segments and use them as parameters to fetch items from a database, like /posts/42 and /posts/42/edit. Bullet has a special param handler for this that takes two arguments: a test callback that validates the parameter type for use, and and a Closure callback. If the test callback returns boolean false, the closure is never executed, and the next path segment or param is tested. If it returns boolean true, the captured parameter is passed to the Closure as the second argument.

Just like regular paths, HTTP method handlers can be nested inside param callbacks, as well as other paths, more parameters, etc.

$app = new Bullet\App(array(
    'template.cfg' => array('path' => __DIR__ . '/templates')
));
$app->path('posts', function($request) use($app) {
    // Integer path segment, like 'posts/42'
    $app->param('int', function($request, $id) use($app) {
        $app->get(function($request) use($id) {
            // View post
            return 'view_' . $id;
        });
        $app->put(function($request) use($id) {
            // Update resource
            $post->data($request->post());
            $post->save();
            return 'update_' . $id;
        });
        $app->delete(function($request) use($id) {
            // Delete resource
            $post->delete();
            return 'delete_' . $id;
        });
    });
    // URL slug (alphanumeric with dashes and underscores)
    $app->param('slug', function($request, $slug) use($app) {
        return $slug; // 'my-post-title'
    });
});
 
// Results of above code
echo $app->run('GET',   '/posts/42'); // 'view_42'
echo $app->run('PUT',   '/posts/42'); // 'update_42'
echo $app->run('DELETE', '/posts/42'); // 'delete_42'
 
echo $app->run('DELETE', '/posts/my-post-title'); // 'my-post-title'
 

Returning JSON (Useful for PHP JSON APIs)

Bullet has built-in support for returning JSON responses. If you return an array from a route handler (callback), Bullet will assume the response is JSON and automatically json_encode the array and return the HTTP response with the appropriate Content-Type: application/json header.

$app->path('/', function($request) use($app) {
    $app->get(function($request) use($app) {
        // Links to available resources for the API
        $data = array(
            '_links' => array(
                'restaurants' => array(
                    'title' => 'Restaurants',
                    'href' => $app->url('restaurants')
                ),
                'events' => array(
                    'title' => 'Events',
                    'href' => $app->url('events')
                )
            )
        );
 
        // Format responders
        $app->format('json', function($request), use($app, $data) {
            return $data; // Auto json_encode on arrays for JSON requests
        });
        $app->format('xml', function($request), use($app, $data) {
            return custom_function_convert_array_to_xml($data);
        });
        $app->format('html', function($request), use($app, $data) {
            return $app->template('index', array('links' => $data));
        });
    });
});
 

HTTP Response Bullet Sends:

Content-Type:application/json

{"_links":{"restaurants":{"title":"Restaurants","href":"http:\/\/yourdomain.local\/restaurants"},"events":{"title":"Events","href":"http:\/\/yourdomain.local\/events"}}}

Nested Requests (HMVC style code re-use)

Since you explicitly return values from Bullet routes instead of sending output directly, nested/sub requests are straightforward and easy. All route handlers will return Bullet\Response instances (even if they return a raw string or other data type, they are wrapped in a response object by the run method), and they can be composed to form a single HTTP response.

$app = new Bullet\App();
$app->path('foo', function($request) use($app) {
    return "foo";
});
$app->path('bar', function($request) use($app) {
    $foo = $app->run('GET', 'foo'); // $foo is now a `Bullet\Response` instance
    return $foo->content() . "bar";
});
echo $app->run('GET', 'bar'); // echos 'foobar' with a 200 OK status
 

Running Tests

To run the Bullet test suite, simply run phpunit in the root of the directory where the bullet files are in. Please make sure to add tests and run the test suite before submitting pull requests for any contributions.

Credits

Bullet - and specifically path-based callbacks that fully embrace HTTP and encourage a more resource-oriented design - is something I have been thinking about for a long time, and was finally moved to create it after seeing @joshbuddy give a presentation on Renee (Ruby) at Confoo 2012 in Montréal.

Fork me on GitHub