標籤:
下載源碼包:
http://www.slimframework.com/
基於Slim的Restful API Sample:
<?phprequire ‘/darjuan/Slim/Slim.php‘;use \Slim\Slim as Slim;Slim::registerAutoloader();$app = new Slim(array( ‘debug‘=>true, ‘templates.path‘ => ‘./templates‘));class BookServiceImpl{ function get_books_list() { $books = array(); for ($i=0; $i < 10; $i++) { $book =array(‘sku_no‘=>‘9SI0000‘.$i,‘book_name‘=>‘php learning‘); $books[$i] = $book; } return $books; }}class APIResponse{ public function show($code,$msg,$data) { header(‘Content-Type:application/json‘); $response = array( ‘code‘=>$code, ‘message‘=>$msg, ‘data‘=>$data ); echo json_encode($response); }}$app->get(‘/books‘,function(){ $books = BookServiceImpl::get_books_list(); APIResponse::show(‘200‘,‘返回成功‘,$books);});$app->get(‘/books/:id‘,function($id){ $books = BookServiceImpl::get_books_list(); try { $book = $books[$id]; } catch (Exception $e) { $book = null; } if(empty($book)) { APIResponse::show(‘404‘,‘資源不存在‘,$book); return; } APIResponse::show(‘200‘,‘返回成功‘,$book);});$app->delete(‘/books/:id‘,function($id){ $books = BookServiceImpl::get_books_list(); unset($books[$id]); APIResponse::show(‘200‘,‘返回成功‘,$books);});$app->run();
Slim - 超輕量級PHP Restful API構建架構