您好,欢迎访问一九零五行业门户网

thinkphp5.0极速搭建restful风格接口层(实例解析)

下面由thinkphp框架教程栏目给大家介绍thinkphp5.0极速搭建restful风格接口层实例,希望对需要的朋友有所帮助!
下面是基于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 -multiviewsrewriteengine onrewritecond %{request_filename} !-drewritecond %{request_filename} !-frewriterule ^(.*)$ 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
<?phpreturn [ // 数据库类型 '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
<?phpuse 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
<?phpnamespace app\index\model;use think\model;class news extends model{ protected $pk = 'id'; //protected static $table = 'news';}
8、新建控制器
application\index\controller\news.php
<?phpnamespace 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
<?phprequire_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
<?phpclass 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
以上就是thinkphp5.0极速搭建restful风格接口层(实例解析)的详细内容。
其它类似信息

推荐信息