<?php
class Home_Service_Session{
	//过期时间
	private $_LEFT_TIME = 3600;

	public function open() {

	}

	public function close(){
	  
	}

	/**
	 * 读
	 */
	public function read($sessid) {
		$where['sessid'] = $sessid;
		$where['expiry'] = array('>',time());
		$info = Home::dao()->getSessions()->get($where);
		return $info['data'];
	}

	/**
	 * 写
	 */
	public function write($sessid , $sessdata) {
		$data = array(
				'expiry'    =>   time()+ $this->_LEFT_TIME,
				'data'      =>   $sessdata,
		);
		$owhere['sessid'] = $sessid;
		$oldData = Home::dao()->getSessions()->get($owhere);
		if($oldData) {
			//更新
			$uwhere['sessid'] = $sessid;
			Home::dao()->getSessions()->update($data, $uwhere);
			return true;
		} else {
			//插入
			$data['sessid'] = $sessid;
			Home::dao()->getSessions()->insert($data);
			return true;
		}
	}

	/**
	 * 指定销毁
	 */
	public function destroy($sessid) {
		$dwhere['sessid'] = $sessid;
		Home::dao()->getSessions()->delete($dwhere);
		return true;
	}

	/**
	 * 销毁过期的数据
	 */
	public function gc() {
		//随机销毁数据,减轻服务器压力
		if( rand(0,3) == 3 ) {
			$where['expiry <'] = time();
			Home::dao()->getSessions()->delete($where);
			return true;
		}
	}
}