[转] 使用slim3快速开发RESTful API
本文转自:https://blog.csdn.net/u011250882/article/details/50101599
版权声明:本文为博主原创文章,转载请注明出处和作者名,尊重别人也是尊重自己 https://blog.csdn.net/u011250882/article/details/50101599
关于slim
在php的框架世界中,除了像symfony、laravel以及zend这样的全栈式的框架之外,还存在着一些微框架,比如基于symfony的silex,基于laravel的lumen,以及这篇博客中要讲到的slim框架,他们不像别的框架那样笨重,而且存在很多的配置项,大多数都是开箱即用,学习周期也很短,看看文档大多在半天内就能掌握它的基本用法。
关于restful
RESTful架构: 
  (1)每一个URI代表一种资源; 
  (2)客户端和服务器之间,传递这种资源的某种表现层; 
  (3)客户端通过四个HTTP动词,对服务器端资源进行操作,实现”表现层状态转化”; 
  (4)GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源。 
RESTful误区: 
(1)URI包含动词; 
  (2)URI中加入版本号。 
注;以上内容出自阮一峰博文:http://www.ruanyifeng.com/blog/2011/09/restful.html 
关于restful只有粗浅的理解,后期读完相关书籍之后再做完善。
slim的安装
这里使用composer安装slim,在命令行下运行如下命令即可安装slim框架:
composer require slim/slim "^3.0"
1
如果使用的是apache服务器,创建.htaccess文件,内容如下:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
再创建index.php文件,内容如下:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App;
$app->get('/', function (Request $request, Response $response) {
    $response->getBody()->write("Hello, world");
return $response;
});
$app->run();
目前的目录结构如下所示:
这时访问http://localhost/slim,即可看到页面上展现出的hello,world。
实战
这里使用这篇文章http://www.codediesel.com/php/create-a-quick-rest-api-using-slim-framework/ 
中提到的例子来实现一个RESTful API的例子。 
创建学生表:
CREATE TABLE IF NOT EXISTS `students` (
  `student_id` int(10) NOT NULL auto_increment,
  `score` int(10) default '0',
  `first_name` varchar(50) default NULL,
  `last_name` varchar(50) default NULL,
  PRIMARY KEY  (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
这里我们手动新增了一条记录:
查
相关代码如下:
$app->get('/score/{id}', function (Request $request, Response $response, $args) {
    try
    {
        $db = getDB();
        $sth = $db->prepare("SELECT * FROM students WHERE student_id = :id");
        $sth->bindParam(':id', $args['id'], PDO::PARAM_INT);
        $sth->execute();
        $student = $sth->fetch(PDO::FETCH_ASSOC);
if($student) {
            $response = $response->withStatus(200)->withHeader('Content-type', 'application/json');
            $response->getBody()->write(json_encode(
                [
                    'status' => 200,
                    'error' => '',
                    'datas' => $student
                ]
            ));
        } else {
            $response = $response->withStatus(404)->withHeader('Content-type', 'application/json');
            $response->getBody()->write(json_encode(
                [
                    'status' => 404,
                    'error' => 'student could not be found',
                    'datas' => $student
                ]
            ));
        }
        return $response;
        $db = null;
    } catch(PDOException $e) {
        $response = $response->withStatus(500)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
            [
                'status' => 500,
                'error' => $e->getMessage(),
                'datas' => ''
            ]
        ));
        return $response;
        $db = null;
    }
});
获取数据库连接的相关代码如下:
function getDB()
{
    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "";
    $dbname = "test";
$mysql_conn_string = "mysql:host=$dbhost;dbname=$dbname";
    $dbConnection = new PDO($mysql_conn_string, $dbuser, $dbpass);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbConnection;
}
此时通过curl访问http://localhost/slim/score/1,得到:
改 
相关代码如下:
$app->put('/score/{id}', function(Request $request, Response $response, $args) {
    try
    {
        $putDatas = $request->getParsedBody();
        $db = getDB();
        $sth = $db->prepare("UPDATE students SET score = :score WHERE student_id = :id");
$sth->bindParam(':score', $putDatas['score'], PDO::PARAM_INT);
        $sth->bindParam(':id', $args['id'], PDO::PARAM_INT);
        $ret = $sth->execute();
$response = $response->withStatus(200)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
                [
                    'status' => 200,
                    'error' => '',
                    'datas' => 'update successfully'
                ]
            )
        );
        return $response;
        $db = null;
    } catch(PDOException $e) {
        $response = $response->withStatus(500)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
            [
                'status' => 500,
                'error' => $e->getMessage(),
                'datas' => ''
            ]
        ));
        return $response;
        $db = null;
    }
});
此时通过curl访问http://localhost/slim/score/2,得到:
删 
相关代码如下:
$app->delete('/score/{id}', function (Request $request, Response $response, $args) {
    try
    {
        $db = getDB();
        $sth = $db->prepare("DELETE FROM students WHERE student_id = :id");
        $sth->bindParam(':id', $args['id'], PDO::PARAM_INT);
        $sth->execute();
$response = $response->withStatus(200)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
                [
                    'status' => 200,
                    'error' => '',
                    'datas' => 'delete successfully'
                ]
            )
        );
        return $response;
        $db = null;
} catch(PDOException $e) {
        $response = $response->withStatus(500)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
            [
                'status' => 500,
                'error' => $e->getMessage(),
                'datas' => ''
            ]
        ));
        return $response;
        $db = null;
    }
});
此时通过curl访问http://localhost/slim/score/2,得到:
- 增 
相关代码如下:
$app->post('/score', function(Request $request, Response $response, $args) {
    $postDatas = $request->getParsedBody();
    try {
        $db = getDB();
        $sth = $db->prepare("INSERT INTO students (score, first_name, last_name) VALUES (:score, :firstName, :lastName)");
        $sth->bindParam(':score', $postDatas['score'], PDO::PARAM_INT);
        $sth->bindParam(':firstName', $postDatas['firstName'], PDO::PARAM_STR);
        $sth->bindParam(':lastName', $postDatas['lastName'], PDO::PARAM_STR);
        $sth->execute();
$response = $response->withStatus(200)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
                [
                    'status' => 200,
                    'error' => '',
                    'datas' => 'insert successfully'
                ]
            )
        );
        return $response;
        $db = null;
} catch(PDOException $e) {
        $response = $response->withStatus(500)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
            [
                'status' => 500,
                'error' => $e->getMessage(),
                'datas' => ''
            ]
        ));
        return $response;
        $db = null;
    }
});
此时通过curl访问http://localhost/slim/score,得到:
注:这篇博文只是做一个入门案例,示例代码有很多坏味道和不规范的地方。
--------------------- 
作者:dongxie548 
来源:CSDN 
原文:https://blog.csdn.net/u011250882/article/details/50101599 
版权声明:本文为博主原创文章,转载请附上博文链接!
[转] 使用slim3快速开发RESTful API的更多相关文章
- flask开发restful api系列(8)-再谈项目结构
		
上一章,我们讲到,怎么用蓝图建造一个好的项目,今天我们继续深入.上一章中,我们所有的接口都写在view.py中,如果几十个,还稍微好管理一点,假如上百个,上千个,怎么找?所有接口堆在一起就显得杂乱无章 ...
 - flask开发restful api
		
flask开发restful api 如果有几个原因可以让你爱上flask这个极其灵活的库,我想蓝图绝对应该算上一个,部署蓝图以后,你会发现整个程序结构非常清晰,模块之间相互不影响.蓝图对restfu ...
 - 玩转 SpringBoot 2 快速搭建 | RESTful Api 篇
		
概述 RESTful 是一种架构风格,任何符合 RESTful 风格的架构,我们都可以称之为 RESTful 架构.我们常说的 RESTful Api 是符合 RESTful 原则和约束的 HTTP ...
 - Spring Boot入门系列(二十)快速打造Restful API 接口
		
spring boot入门系列文章已经写到第二十篇,前面我们讲了spring boot的基础入门的内容,也介绍了spring boot 整合mybatis,整合redis.整合Thymeleaf 模板 ...
 - ASP.NET Core Web API 开发-RESTful API实现
		
ASP.NET Core Web API 开发-RESTful API实现 REST 介绍: 符合REST设计风格的Web API称为RESTful API. 具象状态传输(英文:Representa ...
 - 描述怎样通过flask+redis+sqlalchemy等工具,开发restful api
		
flask开发restful api系列(8)-再谈项目结构 摘要: 进一步介绍flask的项目结构,使整个项目结构一目了然.阅读全文 posted @ 2016-06-06 13:54 月儿弯弯02 ...
 - springmvc/springboot开发restful API
		
非rest的url写法: 查询 GET /user/query?name=tom 详情 GET /user/getinfo? 创建 POST /user/create?name=tom 修改 POST ...
 - 使用Spring MVC开发RESTful API
		
第3章 使用Spring MVC开发RESTful API Restful简介 第一印象 左侧是传统写法,右侧是RESTful写法 用url描述资源,而不是行为 用http方法描述行为,使用http状 ...
 - flask开发restful api系列(7)-蓝图与项目结构
		
如果有几个原因可以让你爱上flask这个极其灵活的库,我想蓝图绝对应该算上一个,部署蓝图以后,你会发现整个程序结构非常清晰,模块之间相互不影响.蓝图对restful api的最明显效果就是版本控制:而 ...
 
随机推荐
- JSP与Servlet的关系
			
之前的文章里有说过,其实Servlet比JSP出现的早,JSP的本质就是Servlet,但是一个是jsp页面,一个是java类,硬要说他们的本质是一样的,搁谁都有点难以置信.后面的结论会更加让你吃惊. ...
 - c#项目减少源代码大小
			
这次的代码缩减主要通过了这几个方面 1.bin和obj文件的删除(以前真的不知道,只是通过右键属性发现这些文件太大,然后上网搜索才知道,这些文件在源代码备份的时候是建议删掉的) 删掉的好处: 1.减少 ...
 - 《HTTP权威指南》5-Web服务器
			
各种形状,风格,尺寸的Web服务器 Web服务器会对HTTP请求进行处理并提供响应.Web服务器有着不同的风格,形状和尺寸但是不管功能,外貌,风格有何差异,所有的Web服务器都能够接收请求资源的HTT ...
 - [转]OpenContrail 体系架构文档
			
OpenContrail 体系架构文档 英文原文:http://opencontrail.org/opencontrail-architecture-documentation/ 翻译者:@KkBLu ...
 - Xcopy命令参数使用介绍
			
DOS批处理命令,永远是不朽的命令,不仅功能强大,同时,速度也是最快的!但是,很多新手学习计算机,都已经遗忘了本不该忘记的批处理命令 XCOPY是COPY的扩展,可以把指定的目录连文件和目录结构一并拷 ...
 - Senparc.Weixin SDK 微信公众号 .NET 开发教程 索引
			
Senparc.WeixinSDK从一开始就坚持开源的状态,这个过程中得到了许多朋友的认可和支持. 目前SDK已经达到比较稳定的版本,这个过程中我觉得有必要整理一些思路和经验,和大家一起分享.也欢迎大 ...
 - 使用MXNet的NDArray来处理数据
			
NDArray.ipynb NDArray介绍 机器学习处理的对象是数据,数据一般是由外部传感器(sensors)采集,经过数字化后存储在计算机中,可能是文本.声音,图片.视频等不同形式. 这些数字化 ...
 - C#基础笔记
			
第一章: 1.C#创建程序的基本结构 class 类名 { static void Main(string[]args) { } } 注意:1)namespace2)using3)类名命名规则:字母. ...
 - [Swift-2019力扣杯春季初赛]1. 易混淆数
			
给定一个数字 N,当它满足以下条件的时候返回 true: 把原数字旋转180°以后得到新的数字. 如 0, 1, 6, 8, 9 旋转 180° 以后,得到了新的数字 0, 1, 9, 8, 6 . ...
 - Oracle to_char(参数,'FM990.00')函数
			
遇到一个SQL,记录一下 select to_char(参数,'FM990.00') from 表格 刚看到FM990.00确实不知道什么意思,通过网上资料,知道了 0表示:如果参数(double或者 ...