1. 程式人生 > >php 開發APP介面

php 開發APP介面

APP模擬器:Start BlueStacks;

第一、APP介面簡介

1.1、客戶端app通訊


這種通訊模式類似於BS架構系統相似,但是有區別:

(1):客戶端請求地址是不可見的,是封裝在APP中的;

(2):BS架構返回的是HTML格式資料,而APP返回的是XML和JSON資料格式。

1.2、app通訊格式的區別:

XML定義:擴充套件標記語言,可以用來標記資料、定義資料型別,是一種允許使用者對自己的標記語言進行定義的源語言。XML格式統一,跨平臺和語言,非常適合資料傳輸和通訊。(XML節點不能為數字)

  1. <span style="font-size:18px;"><?xml version=
    "1.0" encoding="UTF-8"?>  
  2. <item>  
  3.     <title>singwa</title>  
  4.     <test id="1"/>  
  5.     <address>beijing</address>  
  6. </item></span>  

JSON定義:JSON一種輕量級的資料交換格式,具有良好的可讀和便於 快速編寫的特徵。可以在不同的平臺之間進行資料交換。json資料相容性高、完全獨立與語言文字格式。

(1):可讀性方面       --->    XML比較好;

(2):生成資料方面   ---->   json比較好;

(3):傳輸速度方面   ---->   json比較好;

第二、封裝通訊介面資料方法:

1.1、PHP生成JSON資料(json_encode只支援UTF-8)

1.2、通訊資料標準模式

  1. <span style="font-size:18px;">code         狀態碼(200,400等)  
  2. message      提示資訊(郵箱格式不正確:資料返回成功等)  
  3. data         返回資料</span>  
1.3、封裝通訊資料方式

JSON封裝通訊方式:

  1. <span style="font-size:18px;"><?php  
  2. class Pesponse {  
  3.     /** 
  4.      * [通過json方式輸出通訊資料] 
  5.      * @param integer $code 狀態碼 
  6.      * @param string $message 提示資訊 
  7.      * @param array $data     資料 
  8.      */
  9.     publicstaticfunction json($code$message=''$data=array()) {  
  10.         if (!is_numeric($code)) {  
  11.             return'';  
  12.         }  
  13.         $result = array(  
  14.             'code'=>$code,  
  15.             'message'=>$message,  
  16.             'data'=>$data
  17.         );  
  18.         echo json_encode($result);  
  19.         exit;  
  20.     }  
  21. }</span>  
XML封裝通訊:

  1. <span style="font-size:18px;"><?php  
  2. class Pesponse {  
  3.     /** 
  4.      * [通過json方式輸出通訊資料] 
  5.      * @param integer $code 狀態碼 
  6.      * @param string $message 提示資訊 
  7.      * @param array $data     資料 
  8.      */
  9.     publicstaticfunction xmlEncode($code$message=''$data=array()) {  
  10.         if (!is_numeric($code)) {  
  11.             return'';  
  12.         }  
  13.         $result = array(  
  14.             'code'=>$code,  
  15.             'message'=>$message,  
  16.             'data'=>$data
  17.         );  
  18.         header("Content-Type:text/xml");  
  19.         $xml = "<?xml version='1.0' encoding='UTF-8'?>\n";  
  20.         $xml .= "<root>\n";  
  21.         $xml .= self::xmlToEocode($result);  
  22.         $xml .= "</root>";  
  23.         echo$xml;  
  24.     }  
  25.     publicstaticfunction xmlToEocode($data) {  
  26.         $xml = $attr = "";   
  27.         foreach($dataas$key=>$val) {  
  28.             if (is_numeric($key)) {  
  29.                 $attr = " id='{$key}'";  
  30.                 $key = "item";  
  31.             }  
  32.             $xml .= "<{$key}{$attr}>";  
  33.             $xml .= is_array($val)?self::xmlToEocode($val):$val;  
  34.             $xml .= "</{$key}>";  
  35.         }  
  36.         return$xml;  
  37.     }  
  38. }  
  39. $data = array(  
  40.     'id'=>"1",  
  41.     'name'=>'singwa',  
  42.     'type'=>array(1,2,3),  
  43. );  
  44. Pesponse::xmlEncode(200,'success',$data);</span>  

綜合通訊方式封裝:(response.php)

  1. <span style="font-size:18px;"><?php  
  2. class Pesponse {  
  3.     const JSON = "json";  
  4.     /** 
  5.      * [通過json方式輸出通訊資料] 
  6.      * @param integer $code   狀態碼 
  7.      * @param string $message 提示資訊 
  8.      * @param array $data     資料 
  9.      * @param string $type    資料型別 
  10.      */
  11.     <span style="color: rgb(255, 0, 0);">publicstaticfunction show($code$message=''$data=array(), $type=self::JSON) {  
  12.         if (!is_numeric($code)) {  
  13.             return"";  
  14.         }  
  15.         $type = isset($_GET['type']) ? $_GET['type'] : self::JSON;  
  16.         $result = array(  
  17.             'code'=>$code,  
  18.             'message'=>$message,  
  19.             'data'=>$data,  
  20.         );  
  21.         if ($type == "json") {  
  22.             self::json($code$message$data); exit;  
  23.         } elseif($type == "array") {  
  24.             var_dump($result);  
  25.         } elseif($type == "xml") {  
  26.             self::xmlEncode($code$message$data);  
  27.             exit;  
  28.         } else {  
  29.             //TODO
  30.         }  
  31.     }</span>  
  32.     /** 
  33.      * [通過json方式輸出通訊資料] 
  34.      * @param integer $code 狀態碼 
  35.      * @param string $message 提示資訊 
  36.      * @param array $data     資料 
  37.      */
  38.     publicstaticfunction json($code$message=''$data=array()) {  
  39.         if (!is_numeric($code)) {  
  40.             return'';  
  41.         }  
  42.         $result = array(  
  43.             'code'=>$code,  
  44.             'message'=>$message,  
  45.             'data'=>$data
  46.         );  
  47.         echo json_encode($result);  
  48.         exit;  
  49.     }  
  50.     publicstaticfunction xmlEncode($code$message=''$data=array()) {  
  51.         if (!is_numeric($code)) {  
  52.             return'';  
  53.         }  
  54.         $result = array(  
  55.             'code'=>$code,  
  56.             'message'=>$message,  
  57.             'data'=>$data
  58.         );  
  59.         header("Content-Type:text/xml");  
  60.         $xml = "<?xml version='1.0' encoding='UTF-8'?>\n";  
  61.         $xml .= "<root>\n";  
  62.         $xml .= self::xmlToEocode($result);  
  63.         $xml .= "</root>";  
  64.         echo$xml;  
  65.     }  
  66.     publicstaticfunction xmlToEocode($data) {  
  67.         $xml = $attr = "";   
  68.         foreach($dataas$key=>$val) {  
  69.             if (is_numeric($key)) {  
  70.                 $attr = " id='{$key}'";  
  71.                 $key = "item";  
  72.             }  
  73.             $xml .= "<{$key}{$attr}>";  
  74.             $xml .= is_array($val)?self::xmlToEocode($val):$val;  
  75.             $xml .= "</{$key}>";  
  76.         }  
  77.         return$xml;  
  78.     }  
  79. }  
  80. $data = array(  
  81.     'id'=>"1",  
  82.     'name'=>'singwa',  
  83.     'type'=>array(1,2,3),  
  84.     'test'=>array(4,5,6=>array(123,'ssss'))  
  85. );  
  86. Pesponse::show(200,'success',$data);</span>  


2.1、PHP生成XML資料:

2.1.1、組裝字串

  1. <span style="font-size:18px;"><?php  
  2. class Pesponse {  
  3.     publicstaticfunction xml() {  
  4.         header("Content-Type:text/xml");  
  5.         $xml = "<?xml version='1.0' encoding='UTF-8'?>\n";  
  6.         $xml .= "<root>\n";  
  7.         $xml .= "<code>200</code>\n";  
  8.         $xml .= "<message>資料返回成功</message>\n";  
  9.         $xml .= "<data>\n";  
  10.         $xml .= "<id>1</id>\n";  
  11.         $xml .= "<name>singwa</name>\n";  
  12.         $xml .= "</data>\n";  
  13.         $xml .= "</root>";  
  14.         echo$xml;  
  15.     }  
  16. }  
  17. Pesponse::xml();</span>  

2.1.2、使用系統類(PHP開發手冊中查詢)

              DOMDocument                  XMLWriter                    SimpleXML

第三、核心技術

3.1、靜態快取(檔案,file.php)

  1. <span style="font-size:18px;"><?php  
  2. class File {  
  3. <span style="white-space:pre">  </span>private$_dir;  
  4. <span style="white-space:pre">  </span>const EXT = '.txt';  
  5. <span style="white-space:pre">  </span>publicfunction __construct(){  
  6. <span style="white-space:pre">      </span>$this->_dir = dirname(__FILE__).'/file/';  
  7. <span style="white-space:pre">  </span>}  
  8. <span style="white-space:pre">  </span>/**  
  9. <span style="white-space:pre">  </span> * @param  [string] $key   [檔名] 
  10. <span style="white-space:pre">  </span> * @param  string $value   [資料] 
  11. <span style="white-space:pre">  </span> * @param  string $path    [檔案路徑] 
  12. <span style="white-space:pre">  </span> * @return [return]        [位元組數 或者false] 
  13. <span style="white-space:pre">  </span> */
  14. <span style="white-space:pre">  </span>publicfunction cacheData($key$value = ''$cacheTime = 0) {  
  15. <span style="white-space:pre">      </span>$filename = $this->_dir.$key.self::EXT;  
  16. <span style="white-space:pre">      </span>if ($value !== "") {//將value值寫入快取
  17. <span style="white-space:pre">          </span>if (is_null($value)) {//當 $value為null時,刪除快取
  18. <span style="white-space:pre">              </span>return @unlink($filename);  
  19. <span style="white-space:pre">          </span>}  
  20. <span style="white-space:pre">          </span>$dir = dirname($filename);  
  21. <span style="white-space:pre">          </span>if (!is_dir($dir)) {  
  22. <span style="white-space:pre">              </span>mkdir($dir,0777);  
  23. <span style="white-space:pre">          </span>}  
  24. <span style="white-space:pre">          </span>//"%011d"表示不是11位,補0 
  25. <span style="white-space:pre">          </span>$cacheTime = sprintf('%011d'$cacheTime);  
  26. <span style="white-space:pre">          </span>//如果成功返回資料的位元組數,沒有成功返回false
  27. <span style="white-space:pre">          </span>returnfile_put_contents($filename$cacheTime.json_encode($value));  
  28. <span style="white-space:pre">      </span>}  
  29. <span style="white-space:pre">      </span>//讀取快取資料(在呼叫cacheData方法$value不寫時)
  30. <span style="white-space:pre">      </span>if (!is_file($filename)) {  
  31. <span style="white-space:pre">          </span>return FALSE;  
  32. <span style="white-space:pre">      </span>}  
  33. <span style="white-space:pre">      </span>//獲取快取內容
  34. <span style="white-space:pre">      </span>$contents = file_get_contents($filename);  
  35. <span style="white-space:pre">      </span>//獲取快取時間
  36. <span style="white-space:pre">      </span>$cacheTime = (int)substr($contents,0,11);  
  37. <span style="white-space:pre">      </span>//獲取快取內容
  38. <span style="white-space:pre">      </span>$value = substr($contents,11);  
  39. <span style="white-space:pre">      </span>//判斷快取失效時間
  40. <span style="white-space:pre">      </span>if($cacheTime != 0 && $cacheTime+filemtime($filename)<time()) {  
  41. <span style="white-space:pre">          </span>unlink($filename);  
  42. <span style="white-space:pre">          </span>return FALSE;  
  43. <span style="white-space:pre">      </span>}  
  44. <span style="white-space:pre">      </span>return json_decode($value,true);  
  45. <span style="white-space:pre">      </span>  
  46. <span style="white-space:pre">  </span>}  
  47. }</span>  

第三、定時任務

1.定時任務命令

  1. 1.定時任務服務提供crontab命令來設定服務  
  2. 2.crontab  -e       //編輯某個使用者的cron服務
  3. 3.crontab  -l       //列出某個使用者cron服務的詳細內容
  4. 4.crontab  -r       //刪除某個使用者的cron服務
2、定時任務crontab格式



3、定時任務的crontab例子


第四、APP介面例項

1、單例模式連結資料庫(db.php)

1.1、單例模式三大原則
    (1):建構函式需要標記為非public(防止外部使用new操作符建立物件),單例類不能在其他類中例項化,只能被其自身例項化;
    (2):擁有一個儲存類的例項的靜態成員變數$_instance;
    (3):擁有一個訪問這個例項的公共的靜態方法。

  1. <?php  
  2. class Db {  
  3.     staticprivate$_instance;  
  4.     staticprivate$_connectSource;  
  5.     private$dbConfig = array(  
  6.         'host' => '127.0.0.1',  
  7.         'user' => 'root',  
  8.         'password'=> 'root',  
  9.         'database'=> 'video',  
  10.     );  
  11.     privatefunction __construct() {  
  12.     }  
  13.     //公共的靜態方法
  14.     staticpublicfunction getInstance() {  
  15.         if (!(self::$_instance instanceof self)) {  
  16.             self::$_instance = new self();  
  17.         }  
  18.         return self::$_instance;  
  19.     }  
  20.     //連線資料庫
  21.     publicfunction connect() {  
  22.         if (!self::$_connectSource) {  
  23.             self::$_connectSource = @mysql_connect($this->_dbConfig['host'], $this->_dbConfig['user'], $this->_dbConfig['password']);  
  24.             if (self::$_connectSource) {  
  25.                 thrownew Exception('mysql connect error'.mysql_error());  
  26.             }  
  27.             mysql_select_db($this->_dbConfig['database'], self::$_connectSource);  
  28.             mysql_quert('set names UTF-8', self::$_connectSource);  
  29.         }  
  30.         return self::$_connectSource;  
  31.     }  
  32. }  
  33. //連線資料庫
  34. $connect = Db::getInstance()->connect();  

2、首頁APP介面開發

方案一、 讀取資料庫方式開發 首頁介面(應用場景:資料時效性比較高的系統)

  1. <?php  
  2. require_once('./response.php');  
  3. require_once('./db.php');  
  4. //判斷連結合法性
  5. $page = isset($_GET['page']) ? $_GET['page'] : 1;  
  6. $pageSize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 1;  
  7. if (!is_numeric($page) || !is_numeric($pageSize)) {  
  8.     return Response::show(401,'資料不合法');  
  9. }  
  10. $offset = ($page-1) * $pageSize;  
  11. $sql = "select * from video where status = 1 order by orderby desc limit ".$offset.",".$pageSize;  
  12. //連線資料庫
  13. try {  
  14.     $connect = Db::getInstance()->connect();  
  15. } catch(Exception $e) {  
  16.     return Response::show(403, '資料庫連結失敗');  
  17. }  
  18. $result = mysql_query($sql$connect);  
  19. $videos = array();  
  20. while ($video = mysql_fetch_assoc($result)) {  
  21.     $videos[] = $video;  
  22. }  
  23. if ($videos) {  
  24.     return Response::show(200, '首頁獲取資料成功'$videos);  
  25. else {  
  26.     return Response::show(400, '首頁獲取資料失敗'$videos);  
  27. }  

方案二、讀取快取方式開發首頁介面(用途:減少資料庫壓力)(檔案快取)

  1. <?php  
  2. require_once('./response.php');  
  3. require_once('./db.php');  
  4. require_once('./file.php');  
  5. //判斷連結合法性
  6. $page = isset($_GET['page']) ? $_GET['page'] : 1;  
  7. $pageSize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 1;  
  8. if (!is_numeric($page) || !is_numeric($pageSize)) {  
  9.     return Response::show(401,'資料不合法');  
  10. }  
  11. $offset = ($page-1) * $pageSize;  
  12. $sql = "select * from video where status = 1 order by orderby desc limit ".$offset.",".$pageSize;  
  13. $cache = new File();  
  14. $videos = array();  
  15. if (!$videos = $cache->cacheData('index_cache'.$page.'-'.$pageSize)) {  
  16.     //連線資料庫
  17.     try {  
  18.         $connect = Db::getInstance()->connect();  
  19.     } catch(Exception $e) {  
  20.         return Response::show(403, '資料庫連結失敗');  
  21.     }  
  22.     $result = mysql_query($sql$connect);  
  23.     while ($video = mysql_fetch_assoc($result)) {  
  24.         $videos[] = $video;  
  25.     }  
  26.     if ($videos) {  
  27.         $cache->cacheData('index_cache'.$page.'-'.$pageSize,$videos,1200);  
  28.     }  
  29. }  
  30. if ($videos) {  
  31.     return Response::show(200, '首頁獲取資料成功'$videos);  
  32. else {  
  33.     return Response::show(400, '首頁獲取資料失敗'$videos);  
  34. }  

方案三、定時讀取快取方式開發首頁介面

  1. <?php  
  2. //讓crontab定時執行的指令碼程式------ */5 * * * * /usr/bin/php /data/www/app/corn.php
  3. require_once('./db.php');  
  4. require_once('./file.php');  
  5. $sql = "select * from video where status = 1 order by orderby desc";  
  6. try {  
  7.     $connect = Db::getInstance()->connect();  
  8. } catch(Exception $e) {  
  9.     file_put_contents('./logs/'.date('y-m-d').'.txt',$e->getMessage());  
  10.     return;  
  11. }  
  12. $result = mysql_query($sql$connect);  
  13. $videos = array();  
  14. while($video = mysql_fetch_assoc($result)) {  
  15.     $videos[] = $video;  
  16. }  
  17. $file = new File();  
  18. if($videos) {  
  19.     $file->cacheData('index_cron_cache',$videos);  
  20. else {  
  21.     file_put_contents('/logs/'.date('y-m-d').'.txt',"沒有相關資料");  
  22. }  
  23. return;  
第四、APP版本升級以及APP演示

1、APP版本升級分析以及資料表設計

檢測升級:首先開啟APP請求初始化介面init.php,檢測是否更新,如果更新下載最新的原始碼包,替換原來的APK,否的話直接返回首頁;

初始化介面init.php要傳遞的引數:app_id:客戶端id(1.安卓,2.iPhone)、version_id:(版本號) 




 2、升級介面開發和演示


處理介面業務(common.php)

  1. <?php  
  2. /** 
  3.  * 處理介面公共業務 
  4.  */
  5. require_once('./response.php');  
  6. require_once('./db.php');  
  7. class Common {  
  8.     public$params;  
  9.     public$app;  
  10.     publicfunction check() {  
  11.         $this->params['app_id'] = $appId = isset($_POST['app_id']) ? $_POST['app_id'] : '';  
  12.         $this->params['version_id'] = $versionId = isset($_POST['version_id']) ? $_POST['version_id'] : '';  
  13.         $this->params['version_mini'] = $versionMini = isset($_POST['version_mini']) ? $_POST['version_mini'] : '';  
  14.         $this->params['did'] = $did = isset($_POST['did']) ? $_POST['did'] : '';  
  15.         $this->params['encrypt_did'] = $encryptDid = isset($_POST['encrypt_did']) ? $_POST['encrypt_did'] : '';  
  16.         if (!is_numeric($appId) || !is_numeric($versionId)) {  
  17.             return Response::show(401, '引數不合法');  
  18.         }  
  19.         //判斷APP是否需要加密
  20.         $this->app = $this->getApp($appId);  
  21.         if (!$this->app) {  
  22.             return Response::show(402, 'app_id不存在');  
  23.         }  
  24.         if ($this->app['is_encryption'] && $encryptDid != md5($did . $this->app['key'])) {  
  25.             return Response::show(403, '沒有許可權');  
  26.         }  
  27.     }  
  28.     publicfunction getApp($id) {  
  29.         $sql<