## Ion: The Lightweight Request Dispatch Framework for Lithium
Ion is a plugin which allows you to implement micro-applications or application services using the Lithium framework. Ion is ideally suited to serving small requests, such as APIs or Ajax queries, where speed is of the essence.
To use Ion in your application, simply install it in your `plugins` directory and include it by adding the following to `config/bootstrap.php` or `webroot/index.php`:
{{{
\lithium\core\Libraries::add('plugin', 'li3_ion');
}}}
You can then implement Ion services by calling the `run()` method of `li3_ion\extensions\http\Dispatcher`, and passing it an array where the keys are Ion-formatted routes and the values are closures which define how requests matching the corresponding route should be handled.
{{{
use \Exception;
use \app\models\Post;
use \li3_ion\exceptions\NotFoundException;
use \li3_ion\extensions\http\Dispatcher;
echo Dispatcher::run(array(
'get /posts/{:id:\d+}.json' => function($request) {
try {
return array(
'status' => 200,
'type' => 'application/json',
'content' => Post::find($request->id)->to('json')
);
} catch (Exception $e) {
throw new NotFoundException();
}
}
));
}}}
### Routing
The syntax for declaring routes in Ion is similar to that of Lithium standard routes, except that Ion routes are prefixed with an HTTP request method name, followed by a space. Routes can then include standard parameters, with optional regular expression match patterns, as in the example.
### Handling requests
Closures used to handle requests in Ion take a single parameter, an instance of the `Request` object, which encapsulates the request details. Ion extends the default Lithium `Request` object so that route parameters are accessible as properties (i.e. `$request->id`), as seen in the example.
In order to successfully handle requests, closures must _either_ return an array containing (at a minimum) `'status'`, `'type'`, and `'content'` keys, and optionally, a `'headers'` key containing an array with additional headers, _or_ an instance of `lithium\action\Response` containing a fully-formed response.
Alternatively, closures can throw exceptions in case of error, or ignore the request, simply by returning null. If a request is ignored, it simply "falls through", out of the scope of Ion. This is useful if you are declaring a Ion service inside of `webroot/index.php`, and wish for requests ignored by Ion to be handled by your application.