thinkphp5.0极速搭建restful风格接口层实例
作为国内最流行的php框架thinkphp,很快就会发布v5.0正式版了,现在还是rc4版本,但已经很强大了
下面是基于ThinkPHP V5.0 RC4框架,以restful风格完成的新闻查询(get)、新闻增加(post)、新闻修改(put)、新闻删除(delete)等server接口层
1、下载ThinkPHP V5.0 RC4版本:http://www.thinkphp.cn/down/797.html
2、配置虚拟域名(非必须,只是为了方便),参考http://blog.csdn.net/nuli888/article/details/51830659
Apache\conf\extra\httpd-vhosts.conf
<VirtualHost *:>
DocumentRoot "D:/webroot/tp5/public"
ServerName www.tp5-restful.com
<Directory "D:/webroot/tp5/public">
DirectoryIndex index.html index.php
AllowOverride All
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
3、开启伪静态支持.htaccess文件
apache方法:
a)在conf目录下httpd.conf中找到下面这行并去掉#
LoadModule rewrite_module modules/mod_rewrite.so
b)将所有AllowOverride None改成AllowOverride All
public\.htaccess文件内容:
<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$]
</IfModule>
4、创建测试数据
tprestful.sql
--
-- 数据库: `tprestful`
-- -- -------------------------------------------------------- --
-- 表的结构 `news`
-- CREATE TABLE IF NOT EXISTS `news` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='新闻表' AUTO_INCREMENT=1; --
-- 转存表中的数据 `news`
-- INSERT INTO `news` (`id`, `title`, `content`) VALUES
(1, '新闻1', '新闻1内容'),
(2, '新闻2', '新闻2内容'),
(3, '新闻3', '新闻3内容'),
(4, '房价又涨了', '据新华社消息:上海均价环比上涨5%');
5、修改数据库配置文件
application\database.php
<?php
return [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'tprestful',
// 用户名
'username' => 'root',
// 密码
'password' => '123456',
// 端口
'hostport' => '',
// 连接dsn
'dsn' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => '',
// 数据库调试模式
'debug' => true,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
// 是否严格检查字段是否存在
'fields_strict' => true,
// 数据集返回类型 array 数组 collection Collection对象
'resultset_type' => 'array',
// 是否自动写入时间戳字段
'auto_timestamp' => false,
// 是否需要进行SQL性能分析
'sql_explain' => false,
];
6、定义restful风格的路由规则,
application\route.php
<?php
use think\Route;
Route::get('/',function(){
return 'Hello,world!';
});
Route::get('news/:id','index/News/read'); //查询
Route::post('news','index/News/add'); //新增
Route::put('news/:id','index/News/update'); //修改
Route::delete('news/:id','index/News/delete'); //删除
//Route::any('new/:id','News/read'); // 所有请求都支持的路由规则
7、新建模型
application\index\model\News.php
<?php
namespace app\index\model;
use think\Model;
class News extends Model{
protected $pk = 'id';
//protected static $table = 'news';
}
8、新建控制器
application\index\controller\News.php
<?php
namespace app\index\controller;
use think\Request;
use think\controller\Rest; class News extends Rest{
public function rest(){
switch ($this->method){
case 'get': //查询
$this->read($id);
break;
case 'post': //新增
$this->add();
break;
case 'put': //修改
$this->update($id);
break;
case 'delete': //删除
$this->delete($id);
break; }
}
public function read($id){
$model = model('News');
//$data = $model::get($id)->getData();
//$model = new NewsModel();
$data=$model->where('id', $id)->find();// 查询单个数据
return json($data);
} public function add(){
$model = model('News');
$param=Request::instance()->param();//获取当前请求的所有变量(经过过滤)
if($model->save($param)){
return json(["status"=>1]);
}else{
return json(["status"=>0]);
}
}
public function update($id){
$model = model('News');
$param=Request::instance()->param();
if($model->where("id",$id)->update($param)){
return json(["status"=>1]);
}else{
return json(["status"=>0]);
}
}
public function delete($id){ $model = model('News');
$rs=$model::get($id)->delete();
if($rs){
return json(["status"=>1]);
}else{
return json(["status"=>0]);
}
}
}
9、测试
a)、访问入口文件,默认在public\index.php
b)、客户端测试restful的get、post、put、delete方法
client\client.php
<?php
require_once './ApiClient.php'; $param = array(
'title' => '房价又涨了',
'content' => '据新华社消息:上海均价环比上涨5%'
);
$api_url = 'http://www.tp5-restful.com/news/4';
$rest = new restClient($api_url, $param, 'get');
$info = $rest->doRequest();
//$status = $rest->status;//获取curl中的状态信息 $api_url = 'http://www.tp5-restful.com/news';
$rest = new restClient($api_url, $param, 'post');
$info = $rest->doRequest(); $api_url = 'http://www.tp5-restful.com/news/4';
$rest = new restClient($api_url, $param, 'put');
$info = $rest->doRequest(); echo '<pre/>';
print_r($info);exit; $api_url = 'http://www.tp5-restful.com/news/4';
$rest = new restClient($api_url, $param, 'delete');
$info = $rest->doRequest();
?>
请求工具类
client\ApiClient.php
<?php
class restClient
{
//请求的token
const token='yangyulong'; //请求url
private $url; //请求的类型
private $requestType; //请求的数据
private $data; //curl实例
private $curl; public $status; private $headers = array();
/**
* [__construct 构造方法, 初始化数据]
* @param [type] $url 请求的服务器地址
* @param [type] $requestType 发送请求的方法
* @param [type] $data 发送的数据
* @param integer $url_model 路由请求方式
*/
public function __construct($url, $data = array(), $requestType = 'get') { //url是必须要传的,并且是符合PATHINFO模式的路径
if (!$url) {
return false;
}
$this->requestType = strtolower($requestType);
$paramUrl = '';
// PATHINFO模式
if (!empty($data)) {
foreach ($data as $key => $value) {
$paramUrl.= $key . '=' . $value.'&';
}
$url = $url .'?'. $paramUrl;
} //初始化类中的数据
$this->url = $url; $this->data = $data;
try{
if(!$this->curl = curl_init()){
throw new Exception('curl初始化错误:');
};
}catch (Exception $e){
echo '<pre>';
print_r($e->getMessage());
echo '</pre>';
} curl_setopt($this->curl, CURLOPT_URL, $this->url);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($this->curl, CURLOPT_HEADER, 1);
} /**
* [_post 设置get请求的参数]
* @return [type] [description]
*/
public function _get() { } /**
* [_post 设置post请求的参数]
* post 新增资源
* @return [type] [description]
*/
public function _post() { curl_setopt($this->curl, CURLOPT_POST, 1); curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data); } /**
* [_put 设置put请求]
* put 更新资源
* @return [type] [description]
*/
public function _put() { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');
} /**
* [_delete 删除资源]
* delete 删除资源
* @return [type] [description]
*/
public function _delete() {
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); } /**
* [doRequest 执行发送请求]
* @return [type] [description]
*/
public function doRequest() {
//发送给服务端验证信息
if((null !== self::token) && self::token){
$this->headers = array(
'Client-Token:'.self::token,//此处不能用下划线
'Client-Code:'.$this->setAuthorization()
);
} //发送头部信息
$this->setHeader(); //发送请求方式
switch ($this->requestType) {
case 'post':
$this->_post();
break; case 'put':
$this->_put();
break; case 'delete':
$this->_delete();
break; default:
curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE);
break;
}
//执行curl请求
$info = curl_exec($this->curl); //获取curl执行状态信息
$this->status = $this->getInfo();
return $info;
} /**
* 设置发送的头部信息
*/
private function setHeader(){
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);
} /**
* 生成授权码
* @return string 授权码
*/
private function setAuthorization(){
$authorization = md5(substr(md5(self::token), 8, 24).self::token);
return $authorization;
}
/**
* 获取curl中的状态信息
*/
public function getInfo(){
return curl_getinfo($this->curl);
} /**
* 关闭curl连接
*/
public function __destruct(){
curl_close($this->curl);
}
}
转:https://blog.csdn.net/nuli888/article/details/51834037
thinkphp5.0极速搭建restful风格接口层实例的更多相关文章
- SpringBoot2.0基础案例(01):环境搭建和RestFul风格接口
一.SpringBoot 框架的特点 1.SpringBoot2.0 特点 1)SpringBoot继承了Spring优秀的基因,上手难度小 2)简化配置,提供各种默认配置来简化项目配置 3)内嵌式容 ...
- 使用SpringBoot编写Restful风格接口
一.简介 Restful是一种对url进行规范的编码风格,通常一个网址对应一个资源,访问形式类似http://xxx.com/xx/{id}/{id}. 举个栗子,当我们在某购物网站上买手机时会 ...
- 『政善治』Postman工具 — 3、补充:restful风格接口的项目说明
目录 (一)RESTful架构风格特点 1.统一接口风格 2.规范的HTTP请求方法 3.HTTP响应码 4.什么是无状态 (二)JSON数据格式说明 1.什么是JSON 2.JSON格式的特点 3. ...
- PHP实现RESTful风格的API实例(三)
接前一篇PHP实现RESTful风格的API实例(二) .htaccess :重写URL,使URL以 /restful/class/1 形式访问文件 Options +FollowSymlinks R ...
- PHP实现RESTful风格的API实例(二)
接前一篇PHP实现RESTful风格的API实例(一) Response.php :包含一个Request类,即输出类.根据接收到的Content-Type,将Request类返回的数组拼接成对应的格 ...
- PHP实现RESTful风格的API实例(一)
最近看了一些关于RESTful的资料,自己动手也写了一个RESTful实例,以下是源码 目录详情: restful/ Request.php 数据操作类 Response.php 输出类 index. ...
- restful风格接口和spring的运用
Restful风格的API是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机 ...
- Yii2+Swagger搭建RESTful风格的API项目
在现有的Advanced Template上搭建RESTful API项目的步骤: 本案例前提说明: 本例中不使用\yii\rest\ActiveController自动创建的API,而是自定义一个A ...
- 第一节:WebApi的纯原生态的RestFul风格接口和路由规则介绍
一. 原生态接口 1. 从默认路由开始分析 在WebApiConfig.cs类中的Register方法中,我们可以看到默认路由如下: 分析:请求地址在 controller 前面需要加上 api/,c ...
随机推荐
- ubuntu常用终端命令
# ctrl + l - 清屏 . cLear# ctrl + c - 终止命令. # ctrl + d - 退出 shell,好像也可以表示EOF. # ctrl + z - 将当前进程置于后台,f ...
- Netty源码学习(四)Netty服务器是如何启动的?
本文会分析Netty服务器的启动过程,采用的范例代码是Netty编写的Echo Server. 0. 声明acceptor与worker 由于Netty采用的reactor模型,所以需要声明两组线程, ...
- ()java jdbc连接
测试使用 jdk-8u191-windows-x64.mysql-8.0.12-winx64.mysql-connector-java-8.0.13.jar 查询 import java.sql.*; ...
- Python_Tips[1] -> 利用 Python 的字典实现 Switch 功能
利用 Python 的字典实现 Switch 功能 Python是没有switch语句的,当遇到需要实现switch语句的功能时,一般可以用if/else进行代替,但是还有一种更加简洁的实现方法,利用 ...
- IE浏览器Cookie信息提取工具Galleta
IE浏览器Cookie信息提取工具Galleta 浏览器Cookie中保存着用户访问网站的各项敏感信息,如用户登录凭证.提取这些信息后,就可以以该用户的身份访问对应的网站.为了方便信息获取,Kal ...
- Mobius反演与积性函数前缀和演学习笔记 BZOJ 4176 Lucas的数论 SDOI 2015 约数个数和
下文中所有讨论都在数论函数范围内开展. 数论函数指的是定义域为正整数域, 且值域为复数域的函数. 数论意义下的和式处理技巧 因子 \[ \sum_{d | n} a_d = \sum_{d | n} ...
- ASP.NET 5基础之中间件
来源https://docs.asp.net/en/latest/fundamentals/middleware.html 一些可以整合进http请求管道的小的应用组件称做中间件.ASP.NET 5集 ...
- 为什么我不使用Kubernetes的Ingress
为什么我不使用Kubernetes的Ingress 很不幸,据我所知Kubernetes的文档不是很完美,这就是为什么有很多同学在使用它的时候会遇到很多的坑,Ingress这个组件就是这些坑中的一个. ...
- JDBCUtils工具类
JdbcUtils.java import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource ...
- 2017.4.19 慕课网-通过自动回复机器人学习mybatis
开发前的分析 1.技能前提 JSP JSTL EL JS/JQUERY Servlet JavaBean JDBC(后期再用mybatis,这样体会更深) MYSQL 2.需求分析和模块划分 (1)基 ...