Thinkphp5.0极速搭建restful风格接口层
yuyutoo 2024-11-16 02:39 7 浏览 0 评论
下面是基于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
相关推荐
- 网络规划建设原来也可以这么简单!
-
废话少说,直接上干货。天气炎热,请各位看官老爷静心阅读。整体思路下图是关于网络建设的所有相关领域,接下来我为大家逐一讲解。网络分层...
- 网络规划设计师笔记-第 1 章 计算机网络原理
-
计算机网络原理1.1计算机网络概论(P1-10)...
- 别输在远见上,网工这样做职业规划,比啥都强
-
01职业中的规划,人生中的buff“职业规划“这个词,其实对很多年轻人,包括曾经年轻的我来说,都不屑一提。...
- 网络规划设计师学习中(个人自学笔记分享1),有一起学习的吗?
-
网络规划设计师,上午考试内容学习:第一章:计算机网络概述(上部分):如果你也在一起学习,那么我们来一起学习吧!坚持1年,争取明年一次性通过!...
- 在微服务中使用 ASP.NET Core 实现事件溯源和 CQRS
-
概述:事件溯源和命令查询责任分离(CQRS)已成为解决微服务设计的复杂性的强大架构模式。基本CQRS表示形式在本文中,我们将探讨ASP.NETCore如何使你能够将事件溯源和CQRS...
- 用 Nginx 部署 ASP.NET Core 应用程序
-
用Nginx部署ASP.NETCore应用程序步骤如下:在Linux中安装.NETCore运行时和Nginx:...
- Asp.net Core启动流程讲解(一)(asp.net core 入门)
-
asp.netcore默认项目包括项目根目录级的Startup.cs、Program.cs、appsettings.json(appsettings.Development.json)launch...
- 十天学会ASP之第五天(十天学会asp教程)
-
学习目的:学会数据库的基本操作1(写入记录)数据库的基本操作无非是:查询记录,写入记录,删除记录,修改记录。今天我们先学习写入记录。先建立一个表单:<formname="form1"met...
- ASP.NET Core 的 WebApplication 类
-
ASP.NETCore提供了3个主机类(Host)。这些类用于配置应用、管理生命周期和启动Web服务。...
- ASP.NET Core中的键控依赖注入(.net依赖注入原理)
-
大家好,我是深山踏红叶,今天我们来聊一聊ASP.NETCore中的FromKeyedServices,它是在.Net8中引入的。这一特性允许通过键(如字符串或枚举)来注册和检索依赖注入(D...
- Asp.net常用方法及request和response-a
-
asp.net教程asp.net常用方法:1、Request.UrlReferrer请求的来源,可以根据这个判断从百度搜的哪个关键词、防下载盗链、防图片盗链,可以伪造(比如迅雷)。(使用全局一般处理...
- asp.net常考面试题(aspnet题库)
-
asp.net常考面试题一,列举ASP.Net页面之间传递值的几种方式?1,使用QueryString,如:......?id=1;response.Redirect()......2,使用Sessi...
- 在Windows系统搭建.NET Core环境并创建运行ASP.NET网站
-
微软于6月27日在红帽DevNation峰会上正式发布了.NETCore1.0、ASP.NET1.0和EntityFrameworkCore1.0,其将全部支持Windows、OSX和...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- mybatis plus (70)
- scheduledtask (71)
- css滚动条 (60)
- java学生成绩管理系统 (59)
- 结构体数组 (69)
- databasemetadata (64)
- javastatic (68)
- jsp实用教程 (53)
- fontawesome (57)
- widget开发 (57)
- vb net教程 (62)
- hibernate 教程 (63)
- case语句 (57)
- svn连接 (74)
- directoryindex (69)
- session timeout (58)
- textbox换行 (67)
- extension_dir (64)
- linearlayout (58)
- vba高级教程 (75)
- iframe用法 (58)
- sqlparameter (59)
- trim函数 (59)
- flex布局 (63)
- contextloaderlistener (56)