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

[php]  view plain  copy
  1. <VirtualHost *:80>  
  2.     DocumentRoot "D:/webroot/tp5/public"  
  3.     ServerName www.tp5-restful.com  
  4.     <Directory "D:/webroot/tp5/public">  
  5.     DirectoryIndex index.html index.php   
  6.     AllowOverride All  
  7.     Order deny,allow  
  8.     Allow from all  
  9.     </Directory>  
  10. </VirtualHost>  

3、开启伪静态支持.htaccess文件
apache方法:
a)在conf目录下httpd.conf中找到下面这行并去掉#
LoadModule rewrite_module modules/mod_rewrite.so
b)将所有AllowOverride None改成AllowOverride All

public\.htaccess文件内容:

[php]  view plain  copy
  1. <IfModule mod_rewrite.c>  
  2. Options +FollowSymlinks -Multiviews  
  3. RewriteEngine on  
  4.   
  5. RewriteCond %{REQUEST_FILENAME} !-d  
  6. RewriteCond %{REQUEST_FILENAME} !-f  
  7. RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1]  
  8. </IfModule>  

4、创建测试数据
tprestful.sql

[php]  view plain  copy
  1. --  
  2. -- 数据库: `tprestful`  
  3. --  
  4.   
  5. -- --------------------------------------------------------  
  6.   
  7. --  
  8. -- 表的结构 `news`  
  9. --  
  10.   
  11. CREATE TABLE IF NOT EXISTS `news` (  
  12.   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,  
  13.   `title` varchar(255) NOT NULL,  
  14.   `content` text NOT NULL,  
  15.   PRIMARY KEY (`id`)  
  16. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='新闻表' AUTO_INCREMENT=1;  
  17.   
  18. --  
  19. -- 转存表中的数据 `news`  
  20. --  
  21.   
  22. INSERT INTO `news` (`id`, `title`, `content`) VALUES  
  23. (1, '新闻1''新闻1内容'),  
  24. (2, '新闻2''新闻2内容'),  
  25. (3, '新闻3''新闻3内容'),  
  26. (4, '房价又涨了''据新华社消息:上海均价环比上涨5%');  

5、修改数据库配置文件
application\database.php

[php]  view plain  copy
  1. <?php  
  2. return [  
  3.     // 数据库类型  
  4.     'type'           => 'mysql',  
  5.     // 服务器地址  
  6.     'hostname'       => '127.0.0.1',  
  7.     // 数据库名  
  8.     'database'       => 'tprestful',  
  9.     // 用户名  
  10.     'username'       => 'root',  
  11.     // 密码  
  12.     'password'       => '123456',  
  13.     // 端口  
  14.     'hostport'       => '',  
  15.     // 连接dsn  
  16.     'dsn'            => '',  
  17.     // 数据库连接参数  
  18.     'params'         => [],  
  19.     // 数据库编码默认采用utf8  
  20.     'charset'        => 'utf8',  
  21.     // 数据库表前缀  
  22.     'prefix'         => '',  
  23.     // 数据库调试模式  
  24.     'debug'          => true,  
  25.     // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)  
  26.     'deploy'         => 0,  
  27.     // 数据库读写是否分离 主从式有效  
  28.     'rw_separate'    => false,  
  29.     // 读写分离后 主服务器数量  
  30.     'master_num'     => 1,  
  31.     // 指定从服务器序号  
  32.     'slave_no'       => '',  
  33.     // 是否严格检查字段是否存在  
  34.     'fields_strict'  => true,  
  35.     // 数据集返回类型 array 数组 collection Collection对象  
  36.     'resultset_type' => 'array',  
  37.     // 是否自动写入时间戳字段  
  38.     'auto_timestamp' => false,  
  39.     // 是否需要进行SQL性能分析  
  40.     'sql_explain'    => false,  
  41. ];  

6、定义restful风格的路由规则,
application\route.php

[php]  view plain  copy
  1. <?php  
  2. use think\Route;  
  3. Route::get('/',function(){  
  4.     return 'Hello,world!';  
  5. });  
  6. Route::get('news/:id','index/News/read');   //查询  
  7. Route::post('news','index/News/add');       //新增  
  8. Route::put('news/:id','index/News/update'); //修改  
  9. Route::delete('news/:id','index/News/delete'); //删除  
  10. //Route::any('new/:id','News/read');        // 所有请求都支持的路由规则  

7、新建模型
application\index\model\News.php

[php]  view plain  copy
  1. <?php  
  2. namespace app\index\model;  
  3. use think\Model;  
  4. class News extends Model{  
  5.     protected $pk = 'id';  
  6.     //protected static $table = 'news';  
  7. }  

8、新建控制器
application\index\controller\News.php

[php]  view plain  copy
  1. <?php  
  2. namespace app\index\controller;  
  3. use think\Request;  
  4. use think\controller\Rest;  
  5.   
  6. class News extends Rest{  
  7.     public function rest(){  
  8.         switch ($this->method){  
  9.             case 'get':     //查询  
  10.                 $this->read($id);  
  11.                 break;  
  12.             case 'post':    //新增  
  13.                 $this->add();  
  14.                 break;  
  15.             case 'put':     //修改  
  16.                 $this->update($id);  
  17.                 break;  
  18.             case 'delete':  //删除  
  19.                 $this->delete($id);  
  20.                 break;  
  21.               
  22.         }  
  23.     }  
  24.     public function read($id){  
  25.         $model = model('News');  
  26.         //$data = $model::get($id)->getData();  
  27.         //$model = new NewsModel();  
  28.         $data=$model->where('id'$id)->find();// 查询单个数据  
  29.         return json($data);  
  30.     }  
  31.       
  32.     public function add(){  
  33.         $model = model('News');  
  34.         $param=Request::instance()->param();//获取当前请求的所有变量(经过过滤)  
  35.         if($model->save($param)){  
  36.             return json(["status"=>1]);  
  37.         }else{  
  38.             return json(["status"=>0]);  
  39.         }  
  40.     }  
  41.     public function update($id){  
  42.         $model = model('News');  
  43.         $param=Request::instance()->param();  
  44.         if($model->where("id",$id)->update($param)){  
  45.             return json(["status"=>1]);  
  46.         }else{  
  47.             return json(["status"=>0]);  
  48.         }  
  49.     }  
  50.     public function delete($id){  
  51.           
  52.         $model = model('News');  
  53.         $rs=$model::get($id)->delete();  
  54.         if($rs){  
  55.             return json(["status"=>1]);  
  56.         }else{  
  57.             return json(["status"=>0]);  
  58.         }  
  59.     }  
  60. }  

9、测试
a)、访问入口文件,默认在public\index.php


b)、客户端测试restful的get、post、put、delete方法
client\client.php 

[php]  view plain  copy
  1. <?php  
  2. require_once './ApiClient.php';  
  3.   
  4. $param = array(  
  5.   'title' => '房价又涨了',  
  6.   'content' => '据新华社消息:上海均价环比上涨5%'  
  7. );  
  8. $api_url = 'http://www.tp5-restful.com/news/4';   
  9. $rest = new restClient($api_url$param'get');  
  10. $info = $rest->doRequest();  
  11. //$status = $rest->status;//获取curl中的状态信息  
  12.   
  13.   
  14. $api_url = 'http://www.tp5-restful.com/news';   
  15. $rest = new restClient($api_url$param'post');  
  16. $info = $rest->doRequest();  
  17.   
  18. $api_url = 'http://www.tp5-restful.com/news/4';   
  19. $rest = new restClient($api_url$param'put');  
  20. $info = $rest->doRequest();  
  21.   
  22. echo '<pre/>';  
  23. print_r($info);exit;  
  24.   
  25. $api_url = 'http://www.tp5-restful.com/news/4';   
  26. $rest = new restClient($api_url$param'delete');  
  27. $info = $rest->doRequest();  
  28. ?>  

请求工具类
client\ApiClient.php

[php]  view plain  copy
  1. <?php  
  2. class restClient  
  3. {  
  4.   //请求的token  
  5.   const token='yangyulong';  
  6.     
  7.   //请求url  
  8.   private $url;  
  9.       
  10.   //请求的类型  
  11.   private $requestType;  
  12.       
  13.   //请求的数据  
  14.   private $data;  
  15.       
  16.   //curl实例  
  17.   private $curl;  
  18.     
  19.   public $status;  
  20.     
  21.   private $headers = array();  
  22.   /** 
  23.    * [__construct 构造方法, 初始化数据] 
  24.    * @param [type] $url     请求的服务器地址 
  25.    * @param [type] $requestType 发送请求的方法 
  26.    * @param [type] $data    发送的数据 
  27.    * @param integer $url_model  路由请求方式 
  28.    */  
  29.   public function __construct($url$data = array(), $requestType = 'get') {  
  30.         
  31.     //url是必须要传的,并且是符合PATHINFO模式的路径  
  32.     if (!$url) {  
  33.       return false;  
  34.     }  
  35.     $this->requestType = strtolower($requestType);  
  36.     $paramUrl = '';  
  37.     // PATHINFO模式  
  38.     if (!empty($data)) {  
  39.       foreach ($data as $key => $value) {  
  40.         $paramUrl.= $key . '=' . $value.'&';  
  41.       }  
  42.       $url = $url .'?'$paramUrl;  
  43.     }  
  44.         
  45.     //初始化类中的数据  
  46.     $this->url = $url;  
  47.         
  48.     $this->data = $data;  
  49.     try{  
  50.       if(!$this->curl = curl_init()){  
  51.         throw new Exception('curl初始化错误:');  
  52.       };  
  53.     }catch (Exception $e){  
  54.       echo '<pre>';  
  55.       print_r($e->getMessage());  
  56.       echo '</pre>';  
  57.     }  
  58.     
  59.     curl_setopt($this->curl, CURLOPT_URL, $this->url);  
  60.     curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);  
  61.     //curl_setopt($this->curl, CURLOPT_HEADER, 1);  
  62.   }  
  63.       
  64.   /** 
  65.    * [_post 设置get请求的参数] 
  66.    * @return [type] [description] 
  67.    */  
  68.   public function _get() {  
  69.     
  70.   }  
  71.       
  72.   /** 
  73.    * [_post 设置post请求的参数] 
  74.    * post 新增资源 
  75.    * @return [type] [description] 
  76.    */  
  77.   public function _post() {  
  78.     
  79.     curl_setopt($this->curl, CURLOPT_POST, 1);  
  80.     
  81.     curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);  
  82.         
  83.   }  
  84.       
  85.   /** 
  86.    * [_put 设置put请求] 
  87.    * put 更新资源 
  88.    * @return [type] [description] 
  89.    */  
  90.   public function _put() {  
  91.         
  92.     curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');  
  93.   }  
  94.       
  95.   /** 
  96.    * [_delete 删除资源] 
  97.    * delete 删除资源 
  98.    * @return [type] [description] 
  99.    */  
  100.   public function _delete() {  
  101.     curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');  
  102.     
  103.   }  
  104.       
  105.   /** 
  106.    * [doRequest 执行发送请求] 
  107.    * @return [type] [description] 
  108.    */  
  109.   public function doRequest() {  
  110.     //发送给服务端验证信息  
  111.     if((null !== self::token) && self::token){  
  112.       $this->headers = array(  
  113.         'Client-Token:'.self::token,//此处不能用下划线  
  114.         'Client-Code:'.$this->setAuthorization()  
  115.       );  
  116.     }  
  117.       
  118.     //发送头部信息  
  119.     $this->setHeader();  
  120.     
  121.     //发送请求方式  
  122.     switch ($this->requestType) {  
  123.       case 'post':  
  124.         $this->_post();  
  125.         break;  
  126.     
  127.       case 'put':  
  128.         $this->_put();  
  129.         break;  
  130.     
  131.       case 'delete':  
  132.         $this->_delete();  
  133.         break;  
  134.     
  135.       default:  
  136.         curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE);  
  137.         break;  
  138.     }  
  139.     //执行curl请求  
  140.     $info = curl_exec($this->curl);  
  141.     
  142.     //获取curl执行状态信息  
  143.     $this->status = $this->getInfo();  
  144.     return $info;  
  145.   }  
  146.     
  147.   /** 
  148.    * 设置发送的头部信息 
  149.    */  
  150.   private function setHeader(){  
  151.     curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);  
  152.   }  
  153.     
  154.   /** 
  155.    * 生成授权码 
  156.    * @return string 授权码 
  157.    */  
  158.   private function setAuthorization(){  
  159.     $authorization = md5(substr(md5(self::token), 8, 24).self::token);  
  160.     return $authorization;  
  161.   }  
  162.   /** 
  163.    * 获取curl中的状态信息 
  164.    */  
  165.   public function getInfo(){  
  166.     return curl_getinfo($this->curl);  
  167.   }  
  168.     
  169.   /** 
  170.    * 关闭curl连接 
  171.    */  
  172.   public function __destruct(){  
  173.     curl_close($this->curl);  
  174.   }  
  175. }  

完整代码从我github下载: https://github.com/phper-hard/tp5-restful


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值