[php]Yii框架下的curl component

php的curl用法网上介绍的很多了,这里整理一下自己的写法

<?php

class EApi extends CComponent {

    const ERROR_INVALID_TOKEN   = 20001;
    const ERROR_MISSING_PARAM   = 20002;
    const ERROR_INVALID_PARAM   = 20003;
    const ERROR_EMPTY_RESPONSE  = 20004;

    const CACHE_DURATION = 3600;

    public $accessToken;
    public $connectTimeout = 1;
    public $timeout = 5;

    protected $_currentUrlId;
    protected $_urls;
    protected $_ch;

    public function init() {
        //非必须
        $ua = "api/0.1"; defined("APP_MODE") && $ua .= "-".APP_MODE;

        $opt = array(
            CURLOPT_RETURNTRANSFER  => TRUE,         // return web page
            CURLOPT_HEADER          => FALSE,        // don't return headers
            CURLOPT_FOLLOWLOCATION  => FALSE,        // follow redirects
            CURLOPT_ENCODING        => "",           // handle all encodings
            CURLOPT_USERAGENT       => $ua,
            CURLOPT_AUTOREFERER     => TRUE,         // set referer on redirect
            CURLOPT_CONNECTTIMEOUT  => $this->connectTimeout,   // timeout on connect
            CURLOPT_TIMEOUT         => $this->timeout,          // timeout on response
            CURLOPT_SSL_VERIFYHOST  => 0,            // don't verify ssl
            CURLOPT_SSL_VERIFYPEER  => FALSE,        //
            CURLOPT_VERBOSE         => FALSE,        //
        );

        $this->_ch = curl_init();
        curl_setopt_array($this->_ch, $opt);
    }

    public function getApiUrl() {
        if (empty($this->_urls)) {
            return null;
        }
        if ($this->_currentUrlId === null) {
            $this->_currentUrlId = array_rand($this->_urls);
        }
        return $this->_urls[$this->_currentUrlId];
    }

    public function clearApiUrl() {
        unset($this->_urls[$this->_currentUrlId]);
        unset($this->_currentUrlId);
    }

    public function setUrls($urls) {
        $this->_urls = array();
        foreach ($urls as $url) {
            if ("http" != parse_url($url, PHP_URL_SCHEME)) {
                Yii::warning("lianjia-feed server is wrong", $url, "application.linajia-feed");
                continue;
            }
            $this->_urls[] = $url;
        }
    }

    public function query($name, array $params=array(), $post = array()) {

        $urlPrefix = $this->getApiUrl();
        if (empty($urlPrefix)) {
            Yii::warning("no valid lianjia-feed server url exists", null, "application.lianjia-feed");
            return false;
        }
        $query = http_build_query($params);
        $url = $urlPrefix . $name . (strpos($urlPrefix . $name, "?") ? "&" : "?") . $query;
        
        $cacheKey = sprintf("%s:%s?%s", "key", $name, $query);
        $ret = Yii::app()->cache->get($cacheKey);
        if ($ret) {
            return $ret;
        }
//         var_dump($url);
//         die();
        $ch = $this->_ch;
        curl_setopt($ch, CURLOPT_URL, $url);
        if($post) {
            $post = http_build_query($post);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        $raw = curl_exec($ch);
        $errno = curl_errno($ch);

        if ($errno == CURLE_COULDNT_CONNECT) {
            Yii::warning("Couldn't connect server.", $this->_urls[$this->_currentUrlId]);
            unset($this->_urls[$this->_currentUrlId]);
            $this->_currentUrlId = null;
            return $this->query($name, $params);
        }

        if ($errno != CURLE_OK) {
            $errstr = curl_error($ch);
            Yii::fatal("HTTP Error: cURL[{$errno}] {$errstr}", null, "application.lianjia-feed");
            return false;
        }

        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        Yii::info(sprintf("HTTP recieved %.1fKB in %.1fms ",
            curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD)/1024,
            curl_getinfo($ch, CURLINFO_TOTAL_TIME)*1000), null, "application.lianjia-feed");

        if ($code != 200) {
            Yii::fatal("HTTP Error: HTTP[{$code}]", null, "application.lianjia-feed");
            Yii::debug("HTTP Error Response:", $raw, "application.lianjia-feed");
            return false;
        }

        if (empty($raw)) {
            Yii::fatal("HTTP Error: Empty response", null, "application.lianjia-feed");
            return false;
        }

        $res = json_decode($raw, true);       
        
        Yii::app()->cache->set($cacheKey, $res["data"], self::CACHE_DURATION);
        return $res["data"];
    }
    
    //接口地址及其参数
    public function getApi($get, $post) {
        //第二个,第三个为get及其post参数
        return $this->query("feed/getNotifyNum", array("get" => $get), array("post" => $post));
    }

另外在config中添加

        'api' => array(
            'class' => 'ext.EApi',
            'urls'  => array(
                'http://172.0.0.1:8090/',  //IP地址
            ),     
        ),

使用的时候直接调用

Yii::app()->api->getApi($get, $post);

《[php]Yii框架下的curl component》有1个想法

发表评论

电子邮件地址不会被公开。 必填项已用*标注


*