php教程 PHP源码 接口调用模型

接口调用模型

Jul 06, 2016 pm 01:28 PM

跳至 [1] [全屏预览]
<?php
/**
 * 项目api接口类文件
 */

class ApiModel extends Cola_Model
{
    /*
     * 表名
     * @var Cola_Model|null
     */
    protected $_table = '';

    /**
     * 是否开启文件缓存[全局]
     *
     * @var bool
     */
    protected $_fileCache = false;

    /**
     *  baseUrl
     *
     * @var string
     */
    protected $baseUrl = '';

    //保留
    protected $appKey = '';

    protected $loginAppId = '';
    protected $accessToken = '';

    /**
     * 初始化
     *
     * @param string $baseUrl 请求接口地址
     */
    public function __construct($baseUrl = '')
    {
        if (!empty($baseUrl)) {
            $this->baseUrl = $baseUrl;
        } else {
            $this->baseUrl = Cola::config('_bigDataApiURL');
        }
        $u2Config = Cola::config('_OAuthU2Config');//从配置文件中获取验证信息
        $this->loginAppId = $u2Config['AppId'];//获取登录用户的信息
        $this->accessToken = 'ef4e3a2b-ae21-4cad-ada8-86ec46a8a83g';//获取登录用户信息
    }

    /**
     * 设置url
     *
     * @param string $url url地址
     */
    public function setBaseUrl($url)
    {
        $this->baseUrl = $url;
    }

    /**
     *  设置AccessToken
     *
     * @param void
     */
    public function setAccessToken($token)
    {
        $this->accessToken = $token;
    }

    /**
     * 开启缓存
     *
     * @param bool $bool
     */
    public function openCache($bool = true)
    {
        $this->_fileCache = $bool;
    }

    /**
     * 获取数据
     *
     * @param      $method 方法名
     * @param array $params 参数
     * @param int $isPost 0 GET,1 POST请求
     * @param bool $cache 缓存
     *
     * @return mixed
     */
    public function getData($method, $params = null, $isPost = 0, $cache = false)
    {
        if (!is_null($isPost)) {
            $params['accessToken'] = $this->accessToken;
            $params['appId'] = $this->loginAppId;
        }
        $url = $this->_getUrl($method, $params, $isPost);
        if (true == $cache || true == $this->_fileCache) {
            return $this->_getCache($url, $params, $isPost);
        }

        return $this->_curlRequest($url, $params, $isPost);
    }

    /**
     * 删除缓存
     *
     * @param      $method 方法名
     * @param null $params 参数
     * @param int  $isPost 0 GET,1 POST请求
     *
     * @return bool
     */
    public function deleteCache($method, $params = null, $isPost = 0)
    {
        $url = $this->_getUrl($method, $params, $isPost);

        $key = $this->_cacheKey($url, $params, $isPost);

        $file = Cola_Com_Cache::factory(Cola::config('_fileCache'));

        return $file->delete($key);
    }

    /**
     * 获取缓存key文件名
     *
     * @param      $method
     * @param null $params
     * @param int  $isPost
     *
     * @return mixed
     */
    public function getCacheFile($method, $params = null, $isPost = 0)
    {
        $url = $this->_getUrl($method, $params, $isPost);

        $file = Cola_Com_Cache::factory(Cola::config('_fileCache'));

        $key = $this->_cacheKey($url, $params, $isPost);

        return $file->getFile($key);
    }

    /**
     * 请求接口URL
     *
     * @param      $method
     * @param null $params
     * @param int  $isPost
     *
     * @return string
     */
    public function getUrl($method, $params = null, $isPost = 0)
    {
        if (!is_null($isPost)) {
            $params['accessToken'] = $this->accessToken;
            $params['appId'] = $this->loginAppId;
        }
        return $this->_getUrl($method, $params, $isPost);
    }

    /**
     * 获取拼接后的请求地址【缓存的key】
     *
     * @param $method 方法名
     * @param $params 参数
     * @param $isPost 0 GET,1 POST请求
     *
     * @return string
     */
    private function _getUrl($method, $params, $isPost)
    {
        $url = $this->baseUrl . $method;
        if ($isPost == 0) {
            if (is_array($params) && !empty($params)) {
                strpos($url, '?') === false ? $tmpParams = "?" : $tmpParams = "&";
                foreach ($params as $key => $value) {
                    $tmpParams .= $key . "=" . urlencode($value) . "&";
                }

                $url .= rtrim($tmpParams, '&');
            }
        }
        return $url;
    }

    /**
     * 获取缓存数据
     *
     * @param string $url    url
     * @param array  $params 参数
     * @param int    $isPost 0 GET,1 POST请求
     *
     * @return mixed
     */
    private function _getCache($url, $params, $isPost)
    {
        $file = Cola_Com_Cache::factory(Cola::config('_fileCache'));

        //缓存的key
        $sKey = $this->_cacheKey($url, $params, $isPost);
        $res = $file->get($sKey);
        if (!$res) {
            $res = $this->_curlRequest($url, $params, $isPost);
            if (false !== $res) {
                $file->set($sKey, $res);
            }
        }

        return $res;
    }

    /**
     * 设置缓存key
     *
     * @param $url
     * @param $params
     * @param $isPost
     *
     * @return string
     */
    private function _cacheKey($url, $params, $isPost)
    {
        return $url . @json_encode($params) . $isPost;
    }

    /**
     * json转换为数组
     *
     * @param string $string
     *
     * @return mixed
     */
    private function _json2array($string)
    {
        if (@$json = @json_decode($string, true)) {
            return $json;
        } else {
            return $string;
        }
    }

    /**
     * curl 请求
     *
     * @param string $url    请求地址
     * @param array  $params 参数【!!仅当POST时有用】
     * @param int    $isPost 0 GET,1 POST请求
     *
     * @return mixed
     */
    private function _curlRequest($url, $params = array(), $isPost = 0)
    {
        header("Content-type: text/html; charset=utf-8");
        set_time_limit(0);
        // echo $url ; echo "<br>";
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt ($curl ,  CURLOPT_TIMEOUT ,  0 );
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36SE 2.X MetaSr 1.0');
        if ($isPost == 1) {
            curl_setopt($curl, CURLOPT_POST, true);
             
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);//所需传的数组用http_bulid_query()函数处理一下,就ok了
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $result = curl_exec($curl);
        $result = $this->_json2array($result);
        return $this->_checkRequestStatus($result, $url, $params);
    }


    /**
     * 检查请求状态
     *
     * 参考地址:http://scmgit.staff.xdf.cn/bigdata/mdm/wikis/error_code
     *
     * @param $result
     * @param $url
     * @param $params
     *
     * @return bool
     */
    private function _checkRequestStatus($result, $url, $params)
    {
        //错误验证
        if (empty($result) || in_array(@$result['status'], array(400, 404, 500))) {

            //写入日志
            $logFile = WEB_ROOT . '../app/' . 'log/api' . DS . date('Y') . DS . date('m') . DS . date('d') . '-error.log';
            $log = Cola_Com::log(array('adapter' => 'File', 'params' => array('file' => $logFile, 'mode' => 0755)));
            $log->log("请求地址:" . $url . " 参数:" . json_encode($params) . " 错误信息:" . json_encode($result));

            return false;
        }
        else{
        	//写入日志
        	$arr  = explode('/', $url);
        	if(in_array('rule', $arr)){
        	$logFile = WEB_ROOT . '../app/' . 'log/api' . DS . date('Y') . DS . date('m') . DS . date('d') . '-su.log';
        	$log = Cola_Com::log(array('adapter' => 'File', 'params' => array('file' => $logFile, 'mode' => 0755)));
        	$log->log("请求地址:" . $url . " 参数:" . json_encode($params) . " 错误信息:" . json_encode($result));
        	}
        }
        return $result;
    }

}
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)