Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Middleware/api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php
/**
* API Middleware Class for the Slim Framework
*
* @author Montana Flynn <montana@montanaflynn.me>
* @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
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The middleware class with the same functionality already exists here: Middleware/Jsonp.php

$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);
}
}
}