用interface關鍵字定義,樣本:
interface video(){
public function getVideos();
public function getCount();//這都是虛擬方法
}
介面的實現:【介面中給的所有方法都必須在樣本中實現】
class movie implements video{
public function getVideo(){
//do something
}
public function getCount(){
//do something
}
}
介面地址??返回介面資料??解析資料??用戶端
APP(通訊)介面:
1、介面地址(http://app.com/api.php?format=xml);
2、介面檔案(api.php,處理一些商務邏輯);
3、介面資料
APP如何進行通訊:
用戶端App觸發??》發送http請求(介面地址)??》伺服器??》返回用戶端
返回的資料格式一般為xml或者json
地址被封裝在app裡面使用者不可見,與一般的web不同
XML:擴充標記語言,節點可以自訂(而HTML內標籤是不可自訂的),格式統一,可跨平台使用,適合通訊和傳輸。
樣本:
singwa
singwa1
beijing
XML可讀性強;JSON產生資料方面、傳輸速度方面強。
介面作用:擷取資料、提交資料。
封裝通訊介面資料方法
JSON方式封裝通訊介面:json_encode()【必須是UTF-8的形式】
樣本:
$arr = {
‘id’ => 1;
‘username => Tom’
}
echo json_encode($arr);
iconv(‘UTF-8’,’GBK’,$data)//用於進行編碼轉化,本例將$data由UTF-8轉化為GBK
通訊資料標準格式
1、code:200 //狀態代碼
2、message //提示資訊
3、data //返回資料
JSON封裝資料方法樣本(response.php):
class Respomse{
public static function json($code,$message = ‘’,$data = array()){
if(!is_numeric($code)){
return ‘’;//如果傳過來的$code不是數字返回空
}
$result = array(
‘code’ => $code,
‘message’ => $message,
‘data’ => $data
);
echo json_encode($result);
exit;
}
}
在其他檔案調用這個介面:
require_once(‘./response.php’);
$arr = array(
‘id’ => 1,
‘name’ => ‘fareise’
);
Response::json(200,’資料返回成功’,’$arr’);//這樣就會返回一個json資料
XML方式封裝介面資料方法
PHP產生XML資料的方法
1、組裝成字串
2、使用系統類別(DomDocument;XMLWriter;SimpleXML)
樣本:
class Response{
public static function xml(){
header(“Content-Type:text/xml”);//將類型轉化為xml的類型
$xml = “\n”
$xml.=”\n”;
$xml.=”200\n”;
$xml.=”200\n”;
......
$xml.=””;
echo $xml;
}
}
XML方式封裝通訊介面
class Response{
public static function xmlEncode($code,$message,$data){
if(!is_numeric($code)){
return ‘’;
}
$result = array(
‘code’ => $code,
‘message’ => $message,
‘data’ => $data,
);
header(“Content-Type:text/xml”);
$xml = “”
$xml .= “”;
$xml .= self::xmlToEncode($result) //通過定義的這個方法對資料進行xm解析
$xml .= “”;
}
publlc static function amlToEncode($data){ // 通過這樣的遍曆將每一條資料寫成標籤
$xml = $attr = “”;
foreach($data as $key => $value){//如果key是數字則轉化為的形式
if(is_numeric($key)){
$attr = “id = ‘{$key}’”;
$key = “item”;
}
$xml .= “<{$key}{$attr}>”;
//如果是數組,採用遞迴的方式把數組內每一個元素都用標籤輸出
$xml .= is_array($value)?self::xmlToEncode($value):$value;
$xml .= “”
}
}
}
調用樣本:
$data = array(
‘id’ => 1,
‘name’ => fareise
‘type => array(4,5,6)’
)
Response::xmlEncode(200,’sucess’,$data);
綜合通訊封裝方法(兩種都支援)
在前兩個方法都寫好的基礎上:
const JSON = ‘json’//設定預設值
public static function show($code,$message = ‘’,$data = array(),$type=self::JSON){
if(!is_numeric($code)){
return ‘’;
}
$type = $_GET[‘format’]?$_GET[‘format’]:self””JSON;
$result = array(
‘code’ => $code,
‘message’ => $message,
‘data’ => $data
);
if($type == ’json’){
self::json($code,$message,$data);
exit;
}elseif($type == ‘array’){
var dump($result)
}elseif($type == ‘xml’){
self::xmlEncode($code,$message,$data);
exit;
}else{
//TODO
}
}