thinkphp5.0極速搭建restful風格接口層(實例解析)

下面由thinkphp框架教程欄目給大家介紹thinkphp5.0極速搭建restful風格接口層實例,希望對需要的朋友有所幫助!

thinkphp5.0極速搭建restful風格接口層(實例解析)

下面是基于ThinkPHP V5.0 RC4框架,以restful風格完成的新聞查詢(get)、新聞增加(post)、新聞修改(put)、新聞刪除(delete)等server接口層。

1、下載ThinkPHP V5.0 RC4版本;

2、配置虛擬域名(非必須,只是為了方便);

Apacheconfextrahttpd-vhosts.conf

立即學習PHP免費學習筆記(深入)”;

<virtualhost> ????DocumentRoot?"D:/webroot/tp5/public" ????ServerName?www.tp5-restful.com ????<directory> 	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> 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、修改數據庫配置文件
applicationdatabase.php

<?php return [     // 數據庫類型     &#39;type&#39;           =>?'mysql', ????//?服務器地址 ????'hostname'???????=&gt;?'127.0.0.1', ????//?數據庫名 ????'database'???????=&gt;?'tprestful', ????//?用戶名 ????'username'???????=&gt;?'root', ????//?密碼 ????'password'???????=&gt;?'123456', ????//?端口 ????'hostport'???????=&gt;?'', ????//?連接dsn ????'dsn'????????????=&gt;?'', ????//?數據庫連接參數 ????'params'?????????=&gt;?[], ????//?數據庫編碼默認采用utf8 ????'charset'????????=&gt;?'utf8', ????//?數據庫表前綴 ????'prefix'?????????=&gt;?'', ????//?數據庫調試模式 ????'debug'??????????=&gt;?true, ????//?數據庫部署方式:0?集中式(單一服務器),1?分布式(主從服務器) ????'deploy'?????????=&gt;?0, ????//?數據庫讀寫是否分離?主從式有效 ????'rw_separate'????=&gt;?false, ????//?讀寫分離后?主服務器數量 ????'master_num'?????=&gt;?1, ????//?指定從服務器序號 ????'slave_no'???????=&gt;?'', ????//?是否嚴格檢查字段是否存在 ????'fields_strict'??=&gt;?true, ????//?數據集返回類型?array?數組?collection?Collection對象 ????'resultset_type'?=&gt;?'array', ????//?是否自動寫入時間戳字段 ????'auto_timestamp'?=&gt;?false, ????//?是否需要進行SQL性能分析 ????'sql_explain'????=&gt;?false, ];

6、定義restful風格的路由規則,
applicationroute.php

<?php use thinkRoute; Route::get(&#39;/&#39;,function(){     return &#39;Hello,world!&#39;; }); Route::get(&#39;news/:id&#39;,&#39;index/News/read&#39;);	//查詢 Route::post(&#39;news&#39;,&#39;index/News/add&#39;); 		//新增 Route::put(&#39;news/:id&#39;,&#39;index/News/update&#39;); //修改 Route::delete(&#39;news/:id&#39;,&#39;index/News/delete&#39;); //刪除 //Route::any(&#39;new/:id&#39;,&#39;News/read&#39;); 		// 所有請求都支持的路由規則

7、新建模型
applicationindexmodelNews.php

<?php namespace appindexmodel; use thinkModel; class News extends Model{ 	protected $pk = &#39;id&#39;; 	//protected static $table = &#39;news&#39;; }

8、新建控制器
applicationindexcontrollerNews.php

<?php namespace appindexcontroller; use thinkRequest; use thinkcontrollerRest;  class News extends Rest{ 	public function rest(){         switch ($this->method){ 			case?'get':?	//查詢 				$this-&gt;read($id); 				break; 			case?'post':	//新增 				$this-&gt;add(); 				break; 			case?'put':		//修改 				$this-&gt;update($id); 				break; 			case?'delete':	//刪除 				$this-&gt;delete($id); 				break; 			 ????????} ????} ????public?function?read($id){ 		$model?=?model('News'); 		//$data?=?$model::get($id)-&gt;getData(); 		//$model?=?new?NewsModel(); 		$data=$model-&gt;where('id',?$id)-&gt;find();//?查詢單個數據 		return?json($data); ????} 	 	public?function?add(){ 		$model?=?model('News'); 		$param=Request::instance()-&gt;param();//獲取當前請求的所有變量(經過過濾) 		if($model-&gt;save($param)){ 			return?json(["status"=&gt;1]); 		}else{ 			return?json(["status"=&gt;0]); 		} ????} 	public?function?update($id){ 		$model?=?model('News'); 		$param=Request::instance()-&gt;param(); 		if($model-&gt;where("id",$id)-&gt;update($param)){ 			return?json(["status"=&gt;1]); 		}else{ 			return?json(["status"=&gt;0]); 		} ????} 	public?function?delete($id){ 		 		$model?=?model('News'); 		$rs=$model::get($id)-&gt;delete(); 		if($rs){ 			return?json(["status"=&gt;1]); 		}else{ 			return?json(["status"=&gt;0]); 		} ????} }

9、測試
a)、訪問入口文件,默認在publicindex.php

b)、客戶端測試restful的get、post、put、delete方法

clientclient.php?

<?php require_once &#39;./ApiClient.php&#39;;  $param = array(   &#39;title&#39; =>?'房價又漲了', ??'content'?=&gt;?'據新華社消息:上海均價環比上漲5%' ); $api_url?=?'http://www.tp5-restful.com/news/4';? $rest?=?new?restClient($api_url,?$param,?'get'); $info?=?$rest-&gt;doRequest(); //$status?=?$rest-&gt;status;//獲取curl中的狀態信息   $api_url?=?'http://www.tp5-restful.com/news';? $rest?=?new?restClient($api_url,?$param,?'post'); $info?=?$rest-&gt;doRequest();  $api_url?=?'http://www.tp5-restful.com/news/4';? $rest?=?new?restClient($api_url,?$param,?'put'); $info?=?$rest-&gt;doRequest();  echo?'<pre class="brush:php;toolbar:false">

‘; print_r($info);exit; $api_url?=?‘http://www.tp5-restful.com/news/4’;? $rest?=?new?restClient($api_url,?$param,?‘delete’); $info?=?$rest->doRequest(); ?>

請求工具類
clientApiClient.php

<?php class restClient {   //請求的token   const token=&#39;yangyulong&#39;;      //請求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 = &#39;get&#39;) {            //url是必須要傳的,并且是符合PATHINFO模式的路徑     if (!$url) {       return false;     }     $this->requestType?=?strtolower($requestType); ????$paramUrl?=?''; ????//?PATHINFO模式 ????if?(!empty($data))?{ ??????foreach?($data?as?$key?=&gt;?$value)?{ ????????$paramUrl.=?$key?.?'='?.?$value.'&amp;'; ??????} ??????$url?=?$url?.'?'.?$paramUrl; ????} ?????? ????//初始化類中的數據 ????$this-&gt;url?=?$url; ?????? ????$this-&gt;data?=?$data; ????try{ ??????if(!$this-&gt;curl?=?curl_init()){ ????????throw?new?Exception('curl初始化錯誤:'); ??????}; ????}catch?(Exception?$e){ ??????echo?'<pre class="brush:php;toolbar:false">';       print_r($e->getMessage());       echo '

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

以上就是

? 版權聲明
THE END
喜歡就支持一下吧
點贊14 分享