<?php

namespace Heanup\Frame\Library;

/**
 * 缓存设置，使用memcache缓存数据
 */
class Memcache extends \Heanup\Frame\Library
{

    /**
     * 获取连接池
     * @return \Memcached
     */
    public function getConnection()
    {
        static $pool = array();
        $connectionName = $this->getFlag(true);
        if (!isset($pool[$connectionName]) || ($pool[$connectionName] == false)) {
            $cfg = $this->getConfig();
            $pool[$connectionName] = $this->connect($cfg);
        }
        return $pool[$connectionName];
    }

    /**
     * 连接Memcache
     * @param $cfg
     * @return \Memcached
     */
    protected function connect($cfg)
    {
        $connection = new \Memcached;
        $connection->setOption(\Memcached::OPT_COMPRESSION, true);
        $connection->setOption(\Memcached::OPT_DISTRIBUTION, true);
        $connection->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
        $connection->setOption(\Memcached::OPT_NO_BLOCK, true);
        $connection->setOption(\Memcached::OPT_CONNECT_TIMEOUT, 50);
        $connection->setOption(\Memcached::OPT_POLL_TIMEOUT, 50);
        $connection->addServers($cfg);
        return $connection;
    }

}
