PHP开发接口,封装方法

接口的主要功能是从服务器端获取数据,然后渲染到客户端

其主要的实现流程一般会经历这样的几个阶段
服务器端----》 数据库|缓存 ----》 调用接口 ----》客户端

在接口数据传输的过程中,一般采用Json或者Xml的数据格式进行传输,json在生成数据方面(json_encode)和传输速度上比较强,xml在数据的可读性能上比较强。

接下来封装一个完整的接口返回数据的公用方法,如下所示:

<?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'?>
";
        $xml .= "<root>
";

        $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}>
";
        }
        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值和过期时间即可,封装的方法如下:

<?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);
    }

  }

 ?>
原文地址:https://www.cnblogs.com/xs-yqz/p/7605776.html