app接口开发(php)
生活随笔
收集整理的這篇文章主要介紹了
app接口开发(php)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.JSON方式封裝通信接口:
封裝: response.php
<?php // JSON方式封裝通信接口 // 定義 response類 class Response {// 定義一個靜態(tài)方法,作用:按json方式產(chǎn)生數(shù)據(jù) // 規(guī)范通信數(shù)據(jù):參數(shù)一:狀態(tài)碼,參數(shù)二:消息提示(初始值為空),參數(shù)三:組裝后的數(shù)據(jù)(初始值為空數(shù)組)// 注釋碼:/*** 按json方式輸出通信數(shù)據(jù)* @param integer(數(shù)字類型) $code 狀態(tài)碼* @param string(字符串類型) $message 提示信息* @param array(數(shù)組類型) $data 數(shù)據(jù)* return(返回值) string(字符串類型)*/public static function json($code,$message = '',$data = array()){// 判斷$code是否為數(shù)字if(!is_numeric($code)){return '';}//將三個參數(shù)組裝成一個新的數(shù)組$result = array('code' => $code,'message' => $message,'data' => $data);// 通過json_encode(),產(chǎn)生json數(shù)據(jù)echo json_encode($result);// exit 終止程序且不輸出exit;} }?>?
調(diào)用:test.php
<?php // 加載Response類文件 require_once('./response.php'); // 定義一個數(shù)組變量 $arr = array('id' => 1,'name' => 'zhangsan' );// 調(diào)用類文件中的json()方法 Response::json(200,'數(shù)據(jù)返回成功',$arr); ?>?
2.XML方式封裝通信接口
2.0.1 PHP生成xml數(shù)據(jù)
封裝: response.php
public static function xml(){// header 發(fā)送一個http頭信息,將類型改為"text/xml",用于暴露xml節(jié)點header("Content-Type:text/xml");// 生成xml數(shù)據(jù)(通過字符串拼接的方法,首先定義一個變量$xml,存儲xml數(shù)據(jù))// \n 用于換行$xml = "<?xml version='1.0' encoding='UTF-8'?>\n"; // 頭信息$xml .= "<root>\n"; // 根節(jié)點$xml .= "<code>200</code>\n"; // 主體1$xml .= "<message>數(shù)據(jù)返回成功</message>\n"; // 主體2$xml .= "<data>\n"; // 主體3$xml .= "<id>1</id>\n";$xml .= "<name>zhangsan</name>\n";$xml .= "</data>\n";$xml .= "</root>";// 輸出拼接后的xml數(shù)據(jù)echo $xml;}?
2.0.2 xml方式封裝通信數(shù)據(jù)接口
封裝: response.php
<?php // 定義 response類 class Response {// xml方式封裝通信接口// 定義一個靜態(tài)方法,作用:按xml方式產(chǎn)生數(shù)據(jù) // 規(guī)范通信數(shù)據(jù):參數(shù)一:狀態(tài)碼,參數(shù)二:消息提示(初始值為空),參數(shù)三:組裝后的數(shù)據(jù)(初始值為空數(shù)組)// 注釋碼:/*** 按xml方式輸出通信數(shù)據(jù)* @param integer(數(shù)字類型) $code 狀態(tài)碼* @param string(字符串類型) $message 提示信息* @param array(數(shù)組類型) $data 數(shù)據(jù)* return(返回值) string(字符串類型)*/public static function xmlEncode($code,$message,$data = array()){// 判斷$code是否為數(shù)字if(!is_numeric($code)){return '';}//將三個參數(shù)組裝成一個新的數(shù)組$result = array('code' => $code,'message' => $message,'data' => $data);// 生成xml數(shù)據(jù)// 發(fā)送header頭信息,用于暴露xml節(jié)點header("Content-Type:text/xml");// 定義變量$xml,用于存儲拼接后的xml數(shù)據(jù)$xml = "<?xml version='1.0' encoding='UTF-8'?>\n"; // 頭信息$xml .= "<root>\n"; // 根節(jié)點// 使用xmlToEncode()方法解析$result$xml .= self::xmlToEncode($result);$xml .= "</root>";// 輸出拼接后的xml數(shù)據(jù)echo $xml;}// 將$result拼接成新的xml數(shù)據(jù)// 參數(shù):$data(新的數(shù)據(jù)),例如:$resultpublic static function xmlToEncode($data){// 解析$result// 定義變量$xml存儲數(shù)據(jù)$xml = "";// 初始化 $attr,當$key不為數(shù)字時,$attr為空$attr = "";// foreach循環(huán)遍歷$data數(shù)組foreach ($data as $key => $value) {// 判斷$key為數(shù)字的情況if(is_numeric($key)){// 添加屬性$attr = "id='{$key}'";$key = "item";}// $key是一個節(jié)點,$value是節(jié)點的一個數(shù)據(jù),使用{}用于識別變量$xml .= "<{$key}{$attr}>\n"; // 開始標簽// $value是數(shù)組,使用遞歸,循環(huán)輸出(判斷是否為數(shù)組,如果是,則再次調(diào)用xmlToEncode方法)// 在一個類的方法(函數(shù))的上下文中,靜態(tài)變量和函數(shù)被訪問使用self:: ,通過is_array()判斷$value是否為數(shù)組$xml .= is_array($value) ? self::xmlToEncode($value):$value; // 節(jié)點的數(shù)據(jù)$xml .= "</{$key}>\n"; // 結(jié)束標簽}// 循環(huán)結(jié)束后,輸出這一塊組裝好的xml數(shù)據(jù)return $xml;} }// 調(diào)用Response類的方法 $data = array('id' => 1,'name' => 'zhangsan' ); Response::xmlEncode(200,'success',$data);?>?
?
3.綜合方式封裝通訊接口:
封裝: response.php
<?php // 定義 response類 class Response {// 綜合方式封裝通信接口// 定義一個靜態(tài)方法,作用:綜合方式產(chǎn)生數(shù)據(jù) // 規(guī)范通信數(shù)據(jù):參數(shù)一:狀態(tài)碼,參數(shù)二:消息提示(初始值為空),參數(shù)三:組裝后的數(shù)據(jù)(初始值為空數(shù)組),參數(shù)四:數(shù)據(jù)類型(初始值為json)// 注釋碼:/*** 按綜合方式輸出通信數(shù)據(jù)* @param integer(數(shù)字類型) $code 狀態(tài)碼* @param string(字符串類型) $message 提示信息* @param array(數(shù)組類型) $data 數(shù)據(jù)* @param string(字符串類型) $type 數(shù)據(jù)類型* return(返回值) string(字符串類型)*/// 定義常量,默認數(shù)據(jù)類型const JSON = "json";public static function show($code,$message = '',$data = array(),$type = self::JSON){// 判斷$code是否為數(shù)字if(!is_numeric($code)){return '';}// 判斷類型,如果存在,則是通過get方法傳來的值,如果不存在,則是默認值json$type = isset($_GET['format'])?$_GET['format']:self::JSON;//將四個參數(shù)組裝成一個新的數(shù)組數(shù)據(jù)$result = array('code' => $code,'message' => $message,'data' => $data);// 如果數(shù)據(jù)類型為jsonif($type == 'json'){// 調(diào)用json()方法self::json($code,$message,$data);exit;}elseif($type == 'array') {// 如果數(shù)據(jù)類型為array(調(diào)試模式)// 直接輸出$resultvar_dump($result);}elseif($type == 'xml') {// 如果數(shù)據(jù)類型為xml// 調(diào)用xmlEncode()方法self::xmlEncode($code,$message,$data);exit;}else{// 其他類型}}// JSON方式封裝通信接口// 定義一個靜態(tài)方法,作用:按json方式產(chǎn)生數(shù)據(jù) // 規(guī)范通信數(shù)據(jù):參數(shù)一:狀態(tài)碼,參數(shù)二:消息提示(初始值為空),參數(shù)三:組裝后的數(shù)據(jù)(初始值為空數(shù)組)// 注釋碼:/*** 按json方式輸出通信數(shù)據(jù)* @param integer(數(shù)字類型) $code 狀態(tài)碼* @param string(字符串類型) $message 提示信息* @param array(數(shù)組類型) $data 數(shù)據(jù)* return(返回值) string(字符串類型)*/public static function json($code,$message = '',$data = array()){// 判斷$code是否為數(shù)字if(!is_numeric($code)){return '';}//將三個參數(shù)組裝成一個新的數(shù)組$result = array('code' => $code,'message' => $message,'data' => $data);// 通過json_encode(),產(chǎn)生json數(shù)據(jù)echo json_encode($result);// exit 終止程序且不輸出exit;}// xml方式封裝通信接口// 定義一個靜態(tài)方法,作用:按xml方式產(chǎn)生數(shù)據(jù) // 規(guī)范通信數(shù)據(jù):參數(shù)一:狀態(tài)碼,參數(shù)二:消息提示(初始值為空),參數(shù)三:組裝后的數(shù)據(jù)(初始值為空數(shù)組)// 注釋碼:/*** 按xml方式輸出通信數(shù)據(jù)* @param integer(數(shù)字類型) $code 狀態(tài)碼* @param string(字符串類型) $message 提示信息* @param array(數(shù)組類型) $data 數(shù)據(jù)* return(返回值) string(字符串類型)*/public static function xmlEncode($code,$message,$data = array()){// 判斷$code是否為數(shù)字if(!is_numeric($code)){return '';}//將三個參數(shù)組裝成一個新的數(shù)組$result = array('code' => $code,'message' => $message,'data' => $data);// 生成xml數(shù)據(jù)// 發(fā)送header頭信息,用于暴露xml節(jié)點header("Content-Type:text/xml");// 定義變量$xml,用于存儲拼接后的xml數(shù)據(jù)$xml = "<?xml version='1.0' encoding='UTF-8'?>\n"; // 頭信息$xml .= "<root>\n"; // 根節(jié)點// 使用xmlToEncode()方法解析$result$xml .= self::xmlToEncode($result);$xml .= "</root>";// 輸出拼接后的xml數(shù)據(jù)echo $xml;}// 將$result拼接成新的xml數(shù)據(jù)// 參數(shù):$data(新的數(shù)據(jù)),例如:$resultpublic static function xmlToEncode($data){// 解析$result// 定義變量$xml存儲數(shù)據(jù)$xml = "";// 初始化 $attr,當$key不為數(shù)字時,$attr為空$attr = "";// foreach循環(huán)遍歷$data數(shù)組foreach ($data as $key => $value) {// 判斷$key為數(shù)字的情況if(is_numeric($key)){// 添加屬性$attr = "id='{$key}'";$key = "item";}// $key是一個節(jié)點,$value是節(jié)點的一個數(shù)據(jù),使用{}用于識別變量$xml .= "<{$key}{$attr}>\n"; // 開始標簽// $value是數(shù)組,使用遞歸,循環(huán)輸出(判斷是否為數(shù)組,如果是,則再次調(diào)用xmlToEncode方法)// 在一個類的方法(函數(shù))的上下文中,靜態(tài)變量和函數(shù)被訪問使用self:: ,通過is_array()方法判斷$value是否為數(shù)組$xml .= is_array($value) ? self::xmlToEncode($value):$value; // 節(jié)點的數(shù)據(jù)$xml .= "</{$key}>\n"; // 結(jié)束標簽}// 循環(huán)結(jié)束后,輸出這一塊組裝好的xml數(shù)據(jù)return $xml;} }// 調(diào)用Response類的方法 $data = array('id' => 1,'name' => 'zhangsan' ); Response::xmlEncode(200,'success',$data);?>?
調(diào)用:test.php
<?php // 加載Response類文件 require_once('./response.php'); // 定義一個數(shù)組變量 $data = array('id' => 1,'name' => 'zhangsan','type' => array(4,5,6),'test' => array(1,45,67=>array(123,'tsysa')) );// 調(diào)用類文件中的show()方法 Response::show(200,'數(shù)據(jù)返回成功',$data,'json');?>?
?4.將數(shù)據(jù)緩存值指定文件中:
封裝:file.php
<?php // 定義類,作用:處理靜態(tài)緩存 class File {// 定義默認路徑 $_dirprivate $_dir;// 定義文件后綴const EXT = '.txt';// 將默認路徑放在構(gòu)造函數(shù)里面public function __construct(){// dirname(__FILE__)獲取文件當前目錄(即當前php文件所在的目錄)// 設(shè)置默認緩存文件地址$this->_dir = dirname(__FILE__).'/files/';}// 將獲取緩存,生成緩存,刪除緩存 封裝在一個方法中// 參數(shù)一:緩存文件的文件名,參數(shù)二:緩存數(shù)據(jù)(默認值為空),參數(shù)三:保存緩存的文件路徑(默認值為空)public function cacheData($key,$value = '',$path = ''){// 拼裝成一個文件$filename = $this->_dir.$path.$key.self::EXT;// 判斷$values是否存在if($value!==''){// 將value值寫入緩存// 判斷$value是否為null,為null則刪除緩存if(is_null($value)){// unlink() 刪除緩存return @unlink($filename);}// 獲取文件目錄$dir = dirname($filename);// 判斷目錄是否存在,即判斷存儲緩存的文件是否存在,如果不存在,則創(chuàng)建緩存文件if(!is_dir($dir)){// 創(chuàng)建目錄,參數(shù)一:文件目錄名,參數(shù)二:設(shè)置權(quán)限mkdir($dir,0777);}// 將緩存數(shù)據(jù)寫入文件// 參數(shù)一:緩存文件名,參數(shù)二:緩存數(shù)據(jù)(只能是字符串的形式,通過json_encode()轉(zhuǎn)換)return file_put_contents($filename,json_encode($value));}// 判斷$filename是否存在if(!is_file($filename)){return FALSE;}else{// file_get_contents()獲取緩存值// json_decode()將json 轉(zhuǎn)換為數(shù)組形式return json_decode(file_get_contents($filename),true); // 傳入true返回原值}} }?>?
調(diào)用:test.php
<?php // 加載Response類文件 require_once('./file.php'); // 定義一個數(shù)組變量 $data = array('id' => 1,'name' => 'zhangsan','type' => array(4,5,6),'test' => array(1,45,67=>array(123,'tsysa')) );// new一個File類 $file = new File(); // 調(diào)用cacheData()方法 $file->cacheData('index_mk_cache',$data); // 添加緩存 if($file->cacheData('index_mk_cache',$data)){echo "success"; }else{echo "error"; } // 獲取緩存 if($file->cacheData('index_mk_cache'){var_dump($file->cacheData('index_mk_cache'));exit;echo "success"; }else{echo "error"; } // 刪除緩存 if($file->cacheData('index_mk_cache',null)){echo "success"; }else{echo "error"; }?>?
.
// 開始封裝:
通用:db.php
?
<?php // 單例模式連接數(shù)據(jù)庫 // 單例模式(限制類只能擁有一個實例) // 定義一個類 class Db {// 配置數(shù)據(jù)庫private $_dbConfig = array('host' => '127.0.0.1', // 數(shù)據(jù)庫地址'user' => 'root', // 用戶名'password' => '', // 密碼'database' => 'video', // 數(shù)據(jù)庫名);// 定義資源標識符(結(jié)果集)static private $_connectSource;// 用于一個保存類的實例的靜態(tài)成員變量 $_instance// 使用靜態(tài)私有變量保存類的實例static private $_instance;// __construct() 構(gòu)造函數(shù),函數(shù)執(zhí)行時默認執(zhí)行,一般用于初始化// 單例模式規(guī)定構(gòu)造函數(shù)必須是非publicprivate function __construct(){}// 擁有一個訪問這個實例的公共的靜態(tài)方法// 定義getInstance()方法,便于在類的內(nèi)部實例化類static public function getInstance(){// 檢查類有沒有被實例,如果有則返回變量if(!(self::$_instance instanceof self)){// 實例化類self::$_instance = new self();}// 返回一個類的實例return self::$_instance;}// php連接數(shù)據(jù)庫public function connect(){// 判斷資源是否存在if(!self::$_connectSource){// 連接數(shù)據(jù)庫 // @是可以屏蔽函數(shù)執(zhí)行過程中遇到問題而產(chǎn)生的一些錯誤、警告信息,這樣用戶就看不到程序的出錯信息。這樣除了用戶界面會友好一些外,更重要的是安全性,因為屏蔽了出錯文件的路徑等信息。self::$_connectSource = @mysql_connect($this->_dbConfig['host'],$this->_dbConfig['user'],$this->_dbConfig['password']);// 如果沒有返回資源if(!self::$_connectSource){die('數(shù)據(jù)庫連接失敗'.mysql_error());}// 選擇數(shù)據(jù)庫// 參數(shù)一:數(shù)據(jù)庫名稱,參數(shù)二:資源標識符(結(jié)果集)mysql_select_db($this->_dbConfig['database'],self::$_connectSource);// 設(shè)置字符集mysql_query("set names UTF8",self::$_connectSource);}// 返回連接數(shù)據(jù)庫的資源return self::$_connectSource;}}// 調(diào)用 // 數(shù)據(jù)庫的連接,返回結(jié)果集 $connect = Db::getInstance()->connect(); var_dump($connect);?>?
方案一:讀取數(shù)據(jù)庫方式開發(fā)接口(直接連接數(shù)據(jù)庫獲取)
實例:list.php
<?php // 引入接口類 require_once('./response.php'); // 數(shù)據(jù)庫 require_once('./db.php'); // 接口樣例:http://app.com/list.php?page=1&pagesize=10 // 定義頁碼,并判斷是否存在,如果不存在給予默認值 $page = isset($_GET['page']) ? $_GET['page'] : 1; $pageSize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 1; // 驗證傳值是否合法,判斷是否為數(shù)字 if(!is_numeric($page)||!is_numeric($pageSize)){// 生成接口數(shù)據(jù)// 通過return告知其他工程師,下面程序不執(zhí)行return Response::show(401,'數(shù)據(jù)不合法'); } // 編寫SQL語句 // order by XXX desc :倒序排序 // limit 起始位置,數(shù)據(jù)條數(shù) $offset = ($page - 1) * $pageSize; $sql = "select * from video where status = 1 order by orderby desc limit".$offset.",".$pageSize; // 捕獲異常 try{// $connect:連接標識符$connect = Db::getInstance()->connect(); }else(Exception $e){// 提示異常return Response::show(403,'數(shù)據(jù)庫連接失敗'); } // $result:資源標識符(結(jié)果集) $result = mysql_query($sql,$connect); // 定義一個空數(shù)組,用于存儲數(shù)據(jù) $videos = array(); // while循環(huán)輸出所有的數(shù)據(jù) while($video = mysql_fetch_assoc($result)) {// 每次循環(huán),自動生成id,且值會放入$videos數(shù)組中$videos[] = $video; }// 使用Response類中的方法,將$videos中的數(shù)據(jù)轉(zhuǎn)換為json格式 // Response::show('狀態(tài)碼','提示語句','原始數(shù)據(jù)') if($videos){return Response::show(200,'首頁數(shù)據(jù)獲取成功',$videos); }else{return Response::show(400,'首頁數(shù)據(jù)獲取失敗',$videos); } ?>
方案二:讀取緩存方式開發(fā)接口(連接數(shù)據(jù)庫獲取的同時緩存一份,再次獲取時不再連接數(shù)據(jù)庫,而是讀取緩存,可設(shè)置緩存失效時間)
方案三:定時讀取緩存方式開發(fā)接口(通過crontab)
?
總結(jié)
以上是生活随笔為你收集整理的app接口开发(php)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ELK 中的elasticsearch
- 下一篇: 转载牛X文章