下面由thinkphp框架教程欄目給大家介紹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 [ // 數據庫類型 '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風格的路由規則,
applicationroute.php
<?php use thinkRoute; 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、新建模型
applicationindexmodelNews.php
<?php namespace appindexmodel; use thinkModel; class News extends Model{ protected $pk = 'id'; //protected static $table = 'news'; }
8、新建控制器
applicationindexcontrollerNews.php
<?php namespace appindexcontroller; use thinkRequest; use thinkcontrollerRest; 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)、訪問入口文件,默認在publicindex.php
b)、客戶端測試restful的get、post、put、delete方法
clientclient.php?
<?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 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='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 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