Abstract.class.php 3.05 KB
<?php
abstract class Util_Gearman_Abstract {
	
	/**
	 * 超时时间
	 * @var Integer
	 */
	protected $timeout = 0;
	
	/**
	 * 服务器
	 *
	 * @var Array
	 */
	protected $dsn = array();
	
	/**
	 * gearman 对象
	 *
	 * @var Object
	 */
	protected $gearmanObj;
	
	/**
	 * 初始化
	 *
	 * @param String $driver
	 */
	protected function __construct($driver = 'Client') {
		$Gearmandriver = 'Gearman' . ucfirst($driver);
		$this->gearmanObj = new $Gearmandriver();
		if (!isset($this->dsn) || empty($this->dsn)) {
			$this->dsn = Util_Gearman_Dsn::getServers();
		}
		$this->addServers($this->dsn);
	}
	
	/**
	 * 添加多个服务器
	 *
	 * @param array $servers
	 * @return Util_Gearman_Abstract
	 */
	public function addServers(array $servers) {
		$serversStr = implode(',', $servers);
		$status = $this->gearmanObj->addServers($serversStr);
		if ($status == false) {
			throw new Util_Gearman_Exception('init server error : ' . $this->gearmanObj->error() . ' server List: ' . $serversStr);
		}
		return $this;
	}
	
	/**
	 * 添加一个服务器
	 *
	 * @param String $host
	 * @param Integer $port
	 * @return Util_Gearman_Abstract
	 */
	public function addServer($host, $port = 4730) {
		$returns = $this->gearmanObj->addServer($host, $port);
		if ($returns == false) {
			throw new Util_Gearman_Exception(' add server error : ' . $host . ' error mes:' . $this->gearmanObj->error());
		}
		return $this;
	}
	
	/**
	 * 获取gearman 对象
	 *
	 * @return Util_Gearman_Abstract
	 */
	public function gearman() {
		return $this->gearmanObj;
	}
	
	/**
	 * 设置超时时间
	 *
	 * @param Integer $time
	 * @return Util_Gearman_Abstract
	 */
	public function setTimeout($time) {
		$time = intval($time);
		if ($time > 0) {
			$this->timeout = $time;
			$this->gearmanObj->setTimeout($this->timeout);
		}
		return $this;
	}
	
	/**
	 * 获取超时时间
	 *
	 * @return Integer
	 */
	public function getTimeout() {
		return $this->gearmanObj->timeout();
	}
	
	/**
	 * 设置更多参数
	 * @param Integer $options
	 * @return Util_Gearman_Abstract
	 */
	public function setOptions($options) {
		if (!$options) {
			$this->gearmanObj->setOptions($options);
		}
		return $this;
	}
	
	/**
	 * 添加更多参数
	 *
	 * @param Integer $options
	 * @return Util_Gearman_Abstract
	 */
	public function addOptions($options) {
		if (!$options) {
			$this->gearmanObj->addOptions($options);
		}
		return $this;
	}
	
	/**
	 * 复制 Gearman 对象
	 *
	 * @return Object
	 */
	public function clones() {
		return $this->gearmanObj->clone();
	}
	
	/**
	 * 获取返回的错误信息
	 *
	 * @return String
	 */
	public function error() {
		return $this->gearmanObj->error();
	}
	
	/**
	 * 获得errno
	 *
	 * @return Mixed
	 */
	public function getErrno() {
		return $this->gearmanObj->getErrno();
	}
	
	/**
	 * 测试服务器相应
	 *
	 * @param String $workload 参数|数据
	 * @return boll
	 */
	public function test($workload) {
		return $this->gearmanObj->echo($workload);
	}
	
	/**
	 * 返回最后执行码
	 *
	 * @return Mixed
	 */
	public function returnCode() {
		return $this->gearmanObj->returnCode();
	}
	
}