您的位置:首页 > 编程语言 > PHP开发

Slim - 超轻量级PHP Restful API构建框架

2015-03-28 16:32 615 查看
下载源码包:
http://www.slimframework.com/
基于Slim的Restful API Sample:

<?php
require '/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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: