Client.php 2.67 KB
<?php

/**
 * Created by PhpStorm.
 * User: liuziyang
 * Date: 14-4-25
 * Time: 0:46
 */
class Q_Webservice_Yar_Client
{
    private $yarClient;

    private $requestUrl;

    private $url;

    public function __construct($url)
    {
        $this->url = $url;
        $this->requestUrl = empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
        $this->yarClient = new Yar_Client($this->url);
    }

    /**
     * name 可以是: YAR_OPT_PACKAGER, YAR_OPT_PERSISTENT (需要服务端支持keepalive), YAR_OPT_TIMEOUT, YAR_OPT_CONNECT_TIMEOUT
     *
     * YAR_OPT_CONNECT_TIMEOUT, 1000
     *
     * YAR_OPT_PACKAGER, "json"
     *
     * @param $name
     * @param $value
     */
    public function setOpt($name, $value)
    {
        $this->yarClient->setOpt($name, $value);
        return $this;
    }

    /**
     * 设置调用来源
     * @param $referer
     * @return $this
     */
    public function setReferer($referer)
    {
        $this->referer = $referer;
        return $this;
    }

    /**
     * @param $name
     * @param $arguments
     * @return mixed
     */
    public function __call($name, $arguments)
    {
        $callTime = microtime(true);
        try {
            $result = call_user_func_array(array($this->yarClient, $name), $arguments);
            $resultTime = microtime(true);
            ########### 数据包 ###########
            $package = array(
                'result_type' => 'success',
                'function_name' => $name,
                'referer' => $this->requestUrl,
                'service_url' => $this->url,
                'parameter' => $arguments,
                'result' => $result,
                'call_time' => $callTime,
                'result_time' => $resultTime
            );
            ########### 数据包 ###########
            QAid_Logs_Record::yar($package);
        } catch (Yar_Server_Exception $e) {
            $resultTime = microtime(true);
            $package = array(
                'result_type' => 'error',
                'function_name' => $name,
                'referer' => $this->requestUrl,
                'service_url' => $this->url,
                'parameter' => $arguments,
                'call_time' => $callTime,
                'result_time' => $resultTime,
                'exception_data' => array(
                    'type' => $e->getType(),
                    'message' => $e->getMessage()
                )
            );
            QAid_Logs_Record::yar($package);
            $result = $package;
        }
        return $result;
    }

    function call($name, $arguments)
    {
        $result = call_user_func_array(array($this->yarClient, $name), $arguments);
        return $result;
    }
}