Concurrent.php 2.11 KB
<?php
/**
 * User: haisheng.shen@yoho.cn
 * Date: 15-2-9 下午2:08
 */

namespace LibModels;


class Concurrent
{


    /**
     * 添加并行的请求
     * @param $url
     * @param $method
     * @param callable $callback
     * @param null $errorCallback
     */
    public static function call($url, $method, array $parameters = array(), callable $callback = null, callable $errorCallback=null)
    {
        \Yar_Concurrent_Client::call($url, $method, $parameters, $callback, $errorCallback);
    }


    /**
     * 发起请求
     * @param null $callback
     * @param null $errorCallback
     */
    public static function loop(callable $callback=null, callable $errorCallback=null)
    {
        \Yar_Concurrent_Client::loop($callback, $errorCallback);
    }


    /**
     * 非并行yar实例的数组
     * @var array
     */
    protected static $yarInstance = array();

    /**
     * 非并行yar的实例
     * @param $url
     * @return mixed
     */
    public static function single($url, $method, array $parameters =array(), callable $callback=null, callable $errorCallback = null)
    {
        $key = md5($url);
        if (!isset(self::$yarInstance[$key])) {
            self::$yarInstance[$key] = new \Yar_Client($url);
        }
        try {
            $result = call_user_func_array(array(self::$yarInstance[$key], $method), $parameters);
            $callback($result);
        } catch (\Yar_Server_Exception $e) {
            if (!empty($errorCallback)) {
                $errorCallback($e);
            }
        }
    }


    /**
     * 根据参数来选择并行或者非并行
     * @param $url
     * @param $method
     * @param array $params
     * @param callable $callback
     * @param callable $errorCallback
     * @param bool $concurrent
     */
    public static function choise($url, $method, array $params=array(), callable $callback=null, callable $errorCallback = null, $concurrent=true)
    {
        if ($concurrent) {
            self::call($url, $method, $params, $callback, $errorCallback);
        } else {
            self::single($url, $method, $params, $callback, $errorCallback);
        }
    }
}