thinkphp5.0極速搭建restful風格接口層實例

做爲國內最流行的php框架thinkphp,很快就會發布v5.0正式版了,如今仍是rc4版本,但已經很強大了
下面是基於ThinkPHP V5.0 RC4框架,以restful風格完成的新聞查詢(get)、新聞增長(post)、新聞修改(put)、新聞刪除(delete)等server接口層


一、下載ThinkPHP V5.0 RC4版本:http://www.thinkphp.cn/down/797.html 


二、配置虛擬域名(非必須,只是爲了方便),參考http://blog.csdn.net/nuli888/article/details/51830659php

Apache\conf\extra\httpd-vhosts.confhtml

<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>

三、開啓僞靜態支持.htaccess文件
apache方法:
a)在conf目錄下httpd.conf中找到下面這行並去掉#
LoadModule rewrite_module modules/mod_rewrite.so
b)將全部AllowOverride None改爲AllowOverride All

public\.htaccess文件內容:mysql

<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> 

四、建立測試數據
tprestful.sqlweb

--
-- 數據庫: `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%');

五、修改數據庫配置文件
application\database.phpsql

<?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,
];

六、定義restful風格的路由規則,
application\route.phpthinkphp

<?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');         // 全部請求都支持的路由規則

七、新建模型
application\index\model\News.php數據庫

<?php
namespace app\index\model;
use think\Model;
class News extends Model{
    protected $pk = 'id';
    //protected static $table = 'news';
}

八、新建控制器
application\index\controller\News.phpapache

<?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]);
        }
    }
}

九、測試
a)、訪問入口文件,默認在public\index.php


b)、客戶端測試restful的get、post、put、delete方法
client\client.php json

<?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.phpapi

<?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);
  }
}

 

 

轉:https://blog.csdn.net/nuli888/article/details/51834037

相關文章
相關標籤/搜索