PHP開發接口,封裝方法

接口的主要功能是從服務器端獲取數據,而後渲染到客戶端php

其主要的實現流程通常會經歷這樣的幾個階段
服務器端----》 數據庫|緩存 ----》 調用接口 ----》客戶端redis

在接口數據傳輸的過程當中,通常採用Json或者Xml的數據格式進行傳輸,json在生成數據方面(json_encode)和傳輸速度上比較強,xml在數據的可讀性能上比較強。數據庫

接下來封裝一個完整的接口返回數據的公用方法,以下所示:json

<?php
class Response {
    const JSON = "json";
    /**
    * 按綜合方式輸出通訊數據
    * @param integer $code 狀態碼
    * @param string $message 提示信息
    * @param array $data 數據
    * @param string $type 數據類型
    * return string
    */
    public static function show($code, $message = '', $data = array(), $type = self::JSON) {
        if(!is_numeric($code)) {
            return '';
        }

        $type = isset($_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
        }
    }
    /**
    * 按json方式輸出通訊數據
    * @param integer $code 狀態碼
    * @param string $message 提示信息
    * @param array $data 數據
    * return string
    */
    public static function json($code, $message = '', $data = array()) {
        
        if(!is_numeric($code)) {
            return '';
        }

        $result = array(
            'code' => $code,
            'message' => $message,
            'data' => $data
        );

        echo json_encode($result);
        exit;
    }

    /**
    * 按xml方式輸出通訊數據
    * @param integer $code 狀態碼
    * @param string $message 提示信息
    * @param array $data 數據
    * return string
    */
    public static function xmlEncode($code, $message, $data = array()) {
        if(!is_numeric($code)) {
            return '';
        }

        $result = array(
            'code' => $code,
            'message' => $message,
            'data' => $data,
        );

        header("Content-Type:text/xml");
        $xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
        $xml .= "<root>\n";

        $xml .= self::xmlToEncode($result);

        $xml .= "</root>";
        echo $xml;
    }

    public static function xmlToEncode($data) {

        $xml = $attr = "";
        foreach($data as $key => $value) {
            if(is_numeric($key)) {
                $attr = " id='{$key}'";
                $key = "item";
            }
            $xml .= "<{$key}{$attr}>";
            $xml .= is_array($value) ? self::xmlToEncode($value) : $value;
            $xml .= "</{$key}>\n";
        }
        return $xml;
    }

}

緩存在接口中會有大量的使用,關於緩存又分爲靜態緩存和redis/memcache緩存,先說靜態緩存的實現,通常是將數據寫入日誌,查看日誌時用的比較多,即寫入靜態文件中。緩存

<?php

class File {
    private $_dir;

    const EXT = '.txt';

    public function __construct() {
        $this->_dir = dirname(__FILE__) . '/files/';
    }
    public function cacheData($key, $value = '', $cacheTime = 0) {
        $filename = $this->_dir  . $key . self::EXT;

        //寫入文件緩存
        if($value !== '') { // 將value值寫入緩存
            if(is_null($value)) {
                return @unlink($filename);
            }
            $dir = dirname($filename);
            if(!is_dir($dir)) {
                mkdir($dir, 0777);
            }

            $cacheTime = sprintf('%011d', $cacheTime);
            return file_put_contents($filename,$cacheTime . json_encode($value));
        }

        //獲取文件緩存
        if(!is_file($filename)) {
            return FALSE;
        }
        $contents = file_get_contents($filename);
        $cacheTime = (int)substr($contents, 0 ,11);
        $value = substr($contents, 11);
        if($cacheTime !=0 && ($cacheTime + filemtime($filename) < time())) {
            unlink($filename);
            return FALSE;
        }
        return json_decode($value, true);

    }
}

$file = new File();

echo $file->cacheData('test1');

 在接口中經常使用的緩存爲redis緩存,他擁有memcache的全部功能,並且還支持多種數據類型。緩存的數據存放在內存中,讀取速度至關於讀取文件來講更快一些。服務器

redis 緩存的設置只須要選擇數據庫(0-15),直接設置key,value值和過時時間便可,封裝的方法以下:dom

<?php
  class RedisDB
  {
    static $_instance; //存儲對象
    public $handler ;
      private function __construct($dbindex = 0)
      {  
        global $_G ;
        $data = $_G['config']['redis']['redis']['params']; 
        if ( !extension_loaded('redis') ) {
            throw new Exception("REDIS NOT  SUPPORT", 1);
        }      
        $this->handler =  new Redis();  
        //從配置讀取
        $this->handler->connect($data['hostname'],$data['port']);
        $this->handler->auth($data['auth']);
            $this->handler->select($dbindex); 
      }
      public static function getInstance($dbindex = 0){
        if(!isset(self::$_instance[$dbindex]) or  FALSE == (self::$_instance[$dbindex] instanceof self)){
          self::$_instance[$dbindex] = new self($dbindex);
        }
        return self::$_instance[$dbindex];
      }

    /**key value  get**/
    public  function GET($key)
    {
      return  $this->handler->get($key);
    }
    /**key value  set  過時時間爲 $exp**/
    public  function SET($key ,$value ,$exp)
    {
        $this->handler->setex($key ,$exp ,$value );
    }

    /*移除數據$key*/
    public  function REMOVE($key)
    {
        $this->handler->delete($key);

    }

      /*設置數據的過時時間$key*/
    public  function EXPIRE($key ,$exp)
    {
        $this->handler->expire($key ,$exp);
    }

    /**Hash 相關**/

    public  function HGET($domain , $key)
    {
        return $this->handler->hGet($domain , $key);
    }
    public  function HSET ($domain ,$key ,$value )
    {
          $this->handler->hSet($domain , $key);
    }

    public  function HREMOVE($domain ,$key)
    {
        $this->handler->hDel($domain , $key);

    }

     /*插入列表*/
    public  function  PushList($channel,$data)
    {
          $this->handler->lPush($channel,$data);
    }

    /*從列表中獲取*/
    public function  POPList($channel)
    {
        return  $this->handler->lPop($channel);
    }

  }

 ?>
相關文章
相關標籤/搜索