<?php

namespace Heanup\Frame\Package;

/**
 * @author cxm@meitu.com
 * 队列
 */
class RedisQueue
{

    protected static $_instance = NULL;
    protected $redisObj = NULL;
    protected $key = NULL;

    /**
     * 
     * @param unknown $key
     * @param string $config
     * @return self
     */
    public static function getInstance($key, $config = "Redis\\Queue")
    {
        if (empty($key)) {
            return false;
        }
        if (!isset(self::$_instance[$key][$config]) || !(self::$_instance[$key][$config] instanceof self)) {
            self::$_instance[$key][$config] = new self($key, $config);
        }
        return self::$_instance[$key][$config];
    }

    /**
     * 获取队列长度
     * @return int
     */
    public function length()
    {
        $result = $this->getConnection(true)->lLen($this->key);
        return $result;
    }

    /**
     * 插入数据
     * @param $data
     * @return int
     */
    public function push($data)
    {
        $result = $this->getConnection(true)->lPush($this->key, $data);
        return $result;
    }

    /**
     * 取出数据
     * @return string
     */
    public function pop()
    {
        $result = $this->getConnection(true)->rPop($this->key);
        return $result;
    }

    public function delete()
    {
        $result = $this->getConnection(true)->delete($this->key);
        return $result;
    }

    protected function __construct($key, $config)
    {
        $this->key = $key;
        $this->redisObj = new \Heanup\Frame\Library\Redis($config);
    }

    protected function getConnection($isMaster)
    {
        $connection = $this->redisObj->getConnection($isMaster);
        return $connection;
    }

}