码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-03-28 17:00:34      阅读:585      评论:0      收藏:0      [点我收藏+]

标签:

下载源码包:

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

 

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

标签:

原文地址:http://www.cnblogs.com/darjuan/p/nginx-php-slim.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!