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

下载源码包:

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();

 

posted @ 2015-03-28 16:32  darjuan  阅读(1231)  评论(0编辑  收藏  举报