diff --git a/Middleware/api.php b/Middleware/api.php new file mode 100644 index 0000000..b2c14b6 --- /dev/null +++ b/Middleware/api.php @@ -0,0 +1,56 @@ + + * @since 3/10/13 + * + * Simple class to make building API's easier + * + * Usage + * ==== + * + * $api = new \Slim\slim(); + * $api->add(new \Slim\Extras\Middleware\API()); + * + */ + +namespace Slim\Extras\Middleware; + +class API extends \Slim\Middleware +{ + public function call() + { + + // Just to make things easy, we can avoid the 404 page and override with + // helpful error messages. May extend later to find all registered endpoints + $app = $this->app; + + // Change to json + $response = $app->response(); + $response['Content-Type'] = 'application/json'; + + // No Endpoint Specified? + $app->get('/', function() use ($app) { + $app->halt(400, json_encode(array('error'=>'You must specify an endpoint!'))); + }); + + // Cannot Find Endpoint? + $app->get('/:method', function($method) use ($app) { + $app->halt(400, json_encode(array('error'=>'There is no endpoint named '.$method.'!'))); + })->conditions(array('method' => '.+')); + + // Move along to next call + $this->next->call(); + + // But wait! Let's add support for jsonp callbacks + $request = $app->request(); + $callback = $request->params('callback'); + + if(!empty($callback)){ + $app->contentType('application/javascript'); + $jsonp_response = $callback . "(" .$app->response()->body() . ")"; + $app->response()->body($jsonp_response); + } + } +} \ No newline at end of file