Thinkphp5.0极速搭建restful风格接口层
csdh11 2025-02-04 13:36 19 浏览
下面是基于ThinkPHP V5.0 RC4框架,以restful风格完成的新闻查询(get)、新闻增加(post)、新闻修改(put)、新闻删除(delete)等server接口层。
1、下载ThinkPHP V5.0 RC4版本;
2、配置虚拟域名(非必须,只是为了方便);
Apache\conf\extra\httpd-vhosts.conf
<VirtualHost *:80>
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:$1]
</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);
}
}
完整代码从我github下载:
https://github.com/phper-hard/tp5-restful
相关推荐
- pdf怎么在线阅读?这几种在线阅读方法看看
-
pdf怎么在线阅读?我们日常生活中经常使用到pdf文档。这种格式的文档在不同平台和设备上的可移植性,以及保留文档格式和布局的能力都很强。在阅读这种文档的时候,很多人会选择使用在线阅读的方法。在线阅读P...
- PDF比对不再眼花缭乱:开源神器diff-pdf助你轻松揪出差异
-
PDF比对不再眼花缭乱:开源神器diff-pdf助你轻松揪出差异在日常工作和学习中,PDF文件可谓是无处不在。然而,有时我们需要比较两个PDF文件之间的差异,这可不是一件轻松的事情。手动逐页对比简直是...
- 全网爆火!580页Python编程快速上手,零基础也能轻松学会
-
Python虽然一向号称新手友好,但对完全零基础的编程小白来讲,总会在很长时间内,都对某些概念似懂非懂,每次拿起书本教程,都要从第一章看起。对于这种迟迟入不了门的情况,给大家推荐一份简单易懂的入门级教...
- 我的名片能运行Linux和Python,还能玩2048小游戏,成本只要20元
-
晓查发自凹非寺量子位报道|公众号QbitAI猜猜它是什么?印着姓名、职位和邮箱,看起来是个名片。可是右下角有芯片,看起来又像是个PCB电路板。其实它是一台超迷你的ARM计算机,不仅能够运...
- 由浅入深学shell,70页shell脚本编程入门,满满干货建议收藏
-
不会Linux的程序员不是好程序员,不会shell编程就不能说自己会Linux。shell作为Unix第一个脚本语言,结合了延展性和高效的优点,保持独有的编程特色,并不断地优化,使得它能与其他脚本语言...
- 真工程师:20块钱做了张「名片」,可以跑Linux和Python
-
机器之心报道参与:思源、杜伟、泽南对于一个工程师来说,如何在一张名片上宣告自己的实力?在上面制造一台完整的计算机说不定是个好主意。最近,美国一名嵌入式系统工程师GeorgeHilliard的名片...
- 《Linux 命令行大全》.pdf
-
今天跟大家推荐个Linux命令行教程:《TheLinuxCommandLine》,中文译名:《Linux命令行大全》。该书作者出自自美国一名开发者,兼知名Linux博客LinuxCo...
- PDF转换是难题? 搜狗浏览器即开即看
-
由于PDF文件兼容性相当广泛,越来越多的电子图书、产品说明、公司文告、网络资料、电子邮件选择开始使用这种格式来进行内容的展示,以便给用户更好的再现原稿的细节,但需要下载专用阅读器进行转化才能浏览的问题...
- 彻底搞懂 Netty 线程模型
-
点赞再看,养成习惯,微信搜一搜【...
- 2022通俗易懂Redis的线程模型看完就会
-
Redis真的是单线程吗?我们一般说Redis是单线程,是指Redis的网络IO和键值对操作是一个线程完成的,这就是Redis对外提供键值存储服务的主要流程。Redis的其他功能,例如持久化、异步删除...
- 实用C语言编程(第三版)高清PDF
-
编写C程序不仅仅需要语法正确,最关键的是所编代码应该便于维护和修改。现在有很多介绍C语言的著作,但是本书在这一方面的确与众不同,例如在讨论C中运算优先级时,15种级别被归纳为下面两条原则:需要的...
- 手拉手教你搭建redis集群(redis cluster)
-
背景:最近需要使用redis存储数据,但是随着时间的增加,发现原本的单台redis已经不满足要求了,于是就倒腾了一下搭建redistclusterredis集群。好了,话不多说,下面开始展示:...
- 记录处理登录页面显示: HTTP Error 503. The service is unavailable.
-
某天一个系统的登录页面无法显示,显示ServiceUnavailableHTTPError503.Theserviceisunavailable,马上登录服务器上查看IIS是否正常。...
- 黑道圣徒杀出地狱破解版下载 免安装硬盘版
-
游戏名称:黑道圣徒杀出地狱英文名称:SaintsRow:GatOutofHell游戏类型:动作冒险类(ACT)游戏游戏制作:DeepSilverVolition/HighVoltage...
- 一周热门
- 最近发表
- 标签列表
-
- mydisktest_v298 (34)
- document.appendchild (35)
- 头像打包下载 (61)
- acmecadconverter_8.52绿色版 (39)
- word文档批量处理大师破解版 (36)
- server2016安装密钥 (33)
- mysql 昨天的日期 (37)
- parsevideo (33)
- 个人网站源码 (37)
- centos7.4下载 (33)
- mysql 查询今天的数据 (34)
- intouch2014r2sp1永久授权 (36)
- 先锋影音源资2019 (35)
- jdk1.8.0_191下载 (33)
- axure9注册码 (33)
- pts/1 (33)
- spire.pdf 破解版 (35)
- shiro jwt (35)
- sklearn中文手册pdf (35)
- itextsharp使用手册 (33)
- 凯立德2012夏季版懒人包 (34)
- 冒险岛代码查询器 (34)
- 128*128png图片 (34)
- jdk1.8.0_131下载 (34)
- dos 删除目录下所有子目录及文件 (36)