ThinkPHP 使用rest

jerry thinkphp 2015年11月15日 收藏

ThinkPHP的rest与普通controller可以使用一个类共用Controller,只要从RestController继承。这是与yii2不同的地方。

  1. <?php
  2.  
  3. namespace Home\Controller;
  4.  
  5. use Think\Controller\RestController;
  6.  
  7. class HomeController extends RestController {
  8.     protected $allowMethod = array (
  9.             'get',
  10.             'post',
  11.             'put' 
  12.     ); 
  13.     // Rest允许的请求类型列表
  14.     protected $allowType = array (
  15.             'xml',
  16.             'json' 
  17.     ); 
  18.  
  19.     Public function read_json() {
  20.         // 输出id为1的Info的json数据
  21.         $this->response(['a'=>'b'],'json');
  22.     }
  23.  
  24. }

访问:
/Home/read/.json

获取参数的方式:

  1.  public function query($SellId){
  2.         $Form=M('web_hm_sells');
  3.         $data=$Form->find($SellId);
  4.         $this->response($data,'json');
  5.     }
  6.     /**
  7.     * @param int $p    第几页
  8.     * @param int $rows 每页大小
  9.     * page
  10.     * /Hm/Sells/getlist/p/1/rows/5
  11.     */
  12.     public function getlist($p,$rows){
  13.         $Data=M('web_hm_sells');
  14.  
  15.         $map=[];
  16.         $count = $Data->where($map)->count();// 查询满足要求的总记录数 $map表示查询条件
  17.         $Page = new  \Think\Page($count, $rows);// 实例化分页类 传入总记录数
  18.         //var_dump($Page);die();
  19.         $list = $Data->where($map)->order('SellId')->limit($Page->firstRow.','.$Page->listRows)->select();
  20.  
  21.         $this->response([
  22.                 'd'=>[
  23.                 'Table'=>[
  24.                     'rows'=>$list
  25.                 ],
  26.                 'Pagecount'=>($Page->totalRows-1)/$rows+1,
  27.                 'Total'=>$Page->totalRows,
  28.                 'Page'=>$p
  29.                 ]],'json');
  30.     }

请求

  1. $.get('/Home/read/id/2');1

ThinkPHP要求php版本为5.3+,但如果要支持shorthand array写法,需要5.4+。
shorthand array:
$a=[‘key’=>’value’];