• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

php没有开启Memcache扩展类时

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

模拟PHP Memcache 类。
当服务器没有开启Memcache扩展的时候。可以采用本类
使用方法
class_exists('Memcache') or include './Memcache.class.php';
$mem = new Memcache;
$mem->add('key','value');
$mem->get('key')


目前已实现方法
Memcache::connect ( string $host [, int $port ] )
Memcache::get( string $key )
Memcache::add( string $key , mixed $var [, int $expire] )
Memcache::set( string $key , mixed $var [, int $expire] )
Memcache::replace( string $key , mixed $var [, int $expire] )
Memcache::getVersion( void )
Memcache::flush ( void )
Memcache::delete( string $key )
Memcache::close( void )

属性
Memcache::info 服务器相关信息 返回数组

注意 2014年3月28日
本类需要sockets支持
本类的 指定Memcache下标长度超出32字节。自动对key进行MD5

@Version Memcache.class.php 1.1 2014-3-29 04:10:18 $
  bug 修复
  1. 修复必须需要sockets扩展才能使用的缺陷
  2. 代码优化
  3. 添加手动关闭 连接方法

/**
 * Created by Iyoule .
 * 模拟PHP Memcache 类。
 *  当服务器没有开启Memcache扩展的时候。可以采用本类
 *  使用方法
 *            class_exists('Memcache') or include './Memcache.class.php';
 *            $mem = new Memcache;
 *            $mem->add('key','value');
 *            $mem->get('key')
 *  目前已实现方法
 *            Memcache::connect ( string $host [, int $port ] )
 *            Memcache::get( string $key )
 *            Memcache::add( string $key , mixed $var [, int $expire] )
 *            Memcache::set( string $key , mixed $var [, int $expire] )
 *            Memcache::replace( string $key , mixed $var [, int $expire] )
 *            Memcache::getVersion( void )
 *            Memcache::flush ( void )
 *            Memcache::delete( string $key )
 *            Memcache::close( void )           2014-3-29 02:13:19
 *
 * 属性
 *            Memcache::info 服务器相关信息 返回数组
 *
 *  注意
 *      本类需要sockets支持
 *      本类的 指定Memcache下标长度超出32字节。自动对key进行MD5
 *
 * @Version Memcache.class.php 1.1 2014-3-29 04:10:18  $
 *            bug 修复
 *            1. 修复必须需要sockets扩展才能使用的缺陷
 *            2. 代码优化
 *            3. 添加手动关闭 连接方法
 *
 * Version: Memcache.class.php 1.1 $
 * Time: 2014-3-28 上午12:04
 */
class Memcache
{
    /**
     * @var 服务器地址
     */
    public $host;

    /**
     * @var 服务器端口
     */
    public $port;

    /**
     * @var array memcache 服务信息
     */
    private $info = array();

    /**
     * @var null socket资源
     */
    private $socket = null;

    /**
     * @var memcache 命令
     */
    private $command;

    /**
     * @var int 连接超时时间
     */
    private $connect_timeout = 30;
    private $errno;
    private $errstr;

    /**
     * @var mamcache保存数据时长
     */
    private $expire;

    /**
     * @var memcache 保存数据的key 长于32位置将被MD5
     */
    private $key;

    /**
     * @var memcache 保存的值
     */
    private $var;

    /**
     * @var bool 主机是否关闭连接
     */
    private $is_close = false;

    /**
     * @var string 连接函数
     */
    private $connect_method;

    /**
     * 构造方法 判断 根据系统自动判断连接类型
     *  优先级
     *   优先 -> 低
     *  stream_socket_client -> fsockopen -> pfsockopen -> socket_create
     */
    public function __construct()
    {
        if (function_exists('stream_socket_client')) {
            $this->connect_method = 'stream_socket_client';
        } elseif (function_exists('fsockopen')) {
            $this->connect_method = 'fsockopen';
        } elseif (function_exists('pfsockopen')) {
            $this->connect_method = 'pfsockopen';
        } elseif (function_exists('socket_create')) {
            $this->connect_method = 'socket_create';
        }
    }

    /**
     * 从服务端检回一个元素
     * 如果服务端之前有以key作为key存储的元素, Memcache::get()方法此时返回之前存储的值。
     * 你可以给 Memcache::get()方法传递一个数组(多个key)来获取一个数组的元素值,返回的数组仅仅包含从 服务端查找到的key-value对。
     * @param $key 要获取值的key或key数组。
     * @return bool|string 返回key对应的存储元素的字符串值或者在失败或key未找到的时候返回FALSE。
     * @lastTime 2014-3-28 02:44:00
     */
    public function get($key)
    {
        $this->key = isset($key{32}) ? md5($key) : $key;
        $command = "get $key\r\n";
        $this->socket_write($command);
        do {
            $out = $this->socket_read(128);
        } while (strlen($out) == 1);
        $list = preg_split("/\s/", $out);
        if ($list[0] == 'END') return false;
        $string = array();
        $runing = 0;
        do {
            $string[$runing] = $this->socket_read(128);
            substr($string[$runing], 0, 3) == 'END' && strlen($string[$runing]) <= 5 ? $runing = false : $runing++;
        } while ($runing !== false);
        array_pop($string);
        $string = join('', $string);
        $indexOf = 0;
        if ($this->connect_method == 'socket_create') {
            $indexOf = 1;
        }
        $string = substr($string, $indexOf, -2);
        return $string;
    }

    /**
     * 建立连接
     * @param $host memcache 服务器地址
     * @param int $post 端口
     * @lastTime 2014-3-28 02:40:09
     */
    public function connect($host, $post = 11211)
    {
        $this->host = $host;
        $this->port = $post;
        $this->create_socket();
        $this->info();
    }

    /**
     * 魔法方法 构造 add set replace方法
     * @param $method
     * @param $args
     * @return mixed
     * @lastTime 2014-3-28 02:40:28
     */
    public function __call($method, $args)
    {
        if (in_array($method, array('add', 'set', 'replace', 'delete'))) {
            array_unshift($args, $method);
            return call_user_func_array(array($this, 'set__'), $args);
        }
    }

    /**
     * 魔法方法
     * @param $name
     * @return array
     * @lastTime 2014-3-29 04:17:17
     */
    public function __get($name)
    {
        if($name=='info')
            return $this->info;
    }

    /**
     * 针对 魔法方法 add set replace方法进行的处理
     * @param $func 方法名字
     * @param $key memcache的key下标
     * @param $var 设置的值
     * @param int $expire memcache对数据的保存时间 默认24小时
     * @return bool
     * @lastTime 时间
     */
    private function set__($func, $key, $var = null, $expire = 86400)
    {
        if ($this->is_close)
            return false;
        $this->command = trim($func);
        $this->key = isset($key{32}) ? md5($key) : $key;
        if ($func != 'delete') {
            $this->var = trim($var);
            $this->expire = trim($expire);
        }
        return $this->send_do();
    }

    /**
     * 清空memcache的值
     * @return bool
     * @lastTime 2014-3-28 02:43:23
     */
    public function flush()
    {
        $command = "flush_all\r\n";
        $this->socket_write($command);
        if ($this->socket_read(3) == 'OK') {
            return true;
        }
        return false;
    }

    /**
     * Memcache::getVersion — 返回服务器版本信息
     * Memcache::getVersion()返回一个字符串表示的服务端版本号
     * 同样你也可以使用 Memcache::info['version']。
     * @return mixed
     * @lastTime 2014-3-28 02:44:56
     */
    public function getVersion()
    {
        return $this->info['version'];
    }

    /**
     * 对 add set   replace delete 方法进行的处理
     * @return bool
     * @lastTime 2014-3-28 02:45:55
     */
    private function send_do()
    {
        if ($this->command != 'delete') {
            $command = sprintf("%s %s 0 %d %d\r\n", $this->command, $this->key, $this->expire, strlen($this->var));
            $var = sprintf("%s\r\n", $this->var);
            $this->socket_write($command);
            $this->socket_write($var);
        } else {
            $command = sprintf("%s %s\r\n", $this->command, $this->key);
            $this->socket_write($command);
        }
        do {
            $result = $this->socket_read(64);
        } while (strlen($result) == 1);
        $result = str_replace(array("\r", "\n"), '', $result);
        if (substr($result, 0, 5) == 'STORE' || substr($result, 0, 6) == 'DELETE') {
            return true;
        }
        return false;
    }

    /**
     * 创建连接类型
     * @return bool
     * @lastTime 2014-3-29 04:06:15
     */
    private function create_socket()
    {
        $method = $this->connect_method;
        if ($method) {
            switch ($method) {
                case 'socket_create':
                    $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
                    socket_connect($this->socket, $this->host, $this->port);
                    break;
                case 'fsockopen':
                case 'pfsockopen':
                    $this->socket = $method($this->host, $this->port, $this->errno, $this->errstr, $this->connect_timeout);
                    break;
                case 'stream_socket_client':
                    $address = sprintf("tcp://%s:%d", $this->host, $this->port);
                    $this->socket = $method($address, $this->errno, $this->errstr, $this->connect_timeout);
                    break;
            }
        }
        if (is_resource($this->socket))
            return true;
    }

    /**
     * 写入套字节
     * @param $string
     * @return int
     * @lastTime 2014-3-28 02:46:40
     */
    private function socket_write($string)
    {
        $return = false;
        if ($this->connect_method == 'socket_create')
            $return = socket_write($this->socket, $string, strlen($string));
        else if ($this->connect_method)
            $return = fwrite($this->socket, $string);
        return $return;
    }

    /**
     * 读取套字节
     * @param $len 取出的长度
     * @return string
     * @lastTime 2014-3-28 02:47:08
     */
    private function socket_read($len)
    {
        $return = null;
        if ($this->connect_method == 'socket_create')
            $return = socket_read($this->socket, $len, PHP_NORMAL_READ);
        else if ($this->connect_method)
            $return = fgets($this->socket, $len);
        return $return;
    }

    /**
     * 服务器的信息处理
     * @return array
     * @lastTime 2014-3-28 02:47:46
     */
    private function info()
    {
        if (!empty($this->info))
            return $this->info;
        $this->socket_write("stats\r\n");
        $string = array();
        if ($this->connect_method) {
            $runing = 0;
            do {
                $string[$runing] = $this->socket_read(68);
                substr($string[$runing], 0, 3) == 'END' ? $runing = false : $runing++;
            } while ($runing !== false);
            $string = join("\r\n", $string);
            $string = explode("\r\n", $string);
            $string = array_filter($string, function ($value) {
                return isset($value{4});
            });
            $string = array_map(function ($value) {
                return explode(" ", $value);
            }, $string);
            foreach ($string as $val) {
                $this->info[$val[1]] = $val[2];
            }
            return $this->info;
        }
    }

    /**
     * memcache 关闭连接
     * @return bool
     * @lastTime 2014-3-29 01:11:23
     */
    public function close()
    {
        $this->is_close = true;
        return !!$this->socket_write("quit\r\n");
    }

    /**
     * 析构函数 关闭套字节
     */
    public function __destruct()
    {
        if (is_resource($this->socket) && $this->connect_method == 'socket_create')
            socket_close($this->socket);
        else if ($this->connect_method)
            fclose($this->socket);
    }

}

 类二:
memcached-client.php

<?php
//
// +---------------------------------------------------------------------------+
// | memcached client, PHP                                                     |
// +---------------------------------------------------------------------------+
// | Copyright (c) 2003 Ryan T. Dean <[email protected]>                 |
// | All rights reserved.                                                      |
// |                                                                           |
// | Redistribution and use in source and binary forms, with or without        |
// | modification, are permitted provided that the following conditions        |
// | are met:                                                                  |
// |                                                                           |
// | 1. Redistributions of source code must retain the above copyright         |
// |    notice, this list of conditions and the following disclaimer.          |
// | 2. Redistributions in binary form must reproduce the above copyright      |
// |    notice, this list of conditions and the following disclaimer in the    |
// |    documentation and/or other materials provided with the distribution.   |
// |                                                                           |
// | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR      |
// | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
// | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.   |
// | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,          |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT  |
// | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY     |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT       |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF  |
// | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.         |
// +---------------------------------------------------------------------------+
// | Author: Ryan T. Dean <[email protected]>                            |
// | Heavily influenced by the Perl memcached client by Brad Fitzpatrick.      |
// |   Permission granted by Brad Fitzpatrick for relicense of ported Perl     |
// |   client logic under 2-clause BSD license.                                |
// +---------------------------------------------------------------------------+
//
// $TCAnet$
//

/**
 * This is the PHP client for memcached - a distributed memory cache daemon.
 * More information is available at http://www.danga.com/memcached/
 *
 * Usage example:
 *
 * require_once 'memcached.php';
 * 
 * $mc = new memcached(array(
 *              'servers' => array('127.0.0.1:10000', 
 *                                 array('192.0.0.1:10010', 2),
 *                                 '127.0.0.1:10020'),
 *              'debug'   => false,
 *              'compress_threshold' => 10240,
 *              'persistant' => true));
 *
 * $mc->add('key', array('some', 'array'));
 * $mc->replace('key', 'some random string');
 * $val = $mc->get('key');
 *
 * @author  Ryan T. Dean <[email protected]>
 * @package memcached-client
 * @version 0.1.2
 */

// {{{ requirements
// }}}

// {{{ constants
// {{{ flags

/**
 * Flag: indicates data is serialized
 */
define("MEMCACHE_SERIALIZED", 1<<0);

/**
 * Flag: indicates data is compressed
 */
define("MEMCACHE_COMPRESSED", 1<<1);

// }}}

/**
 * Minimum savings to store data compressed
 */
define("COMPRESSION_SAVINGS", 0.20);

// }}}

// {{{ class memcached
/**
 * memcached client class implemented using (p)fsockopen()
 *
 * @author  Ryan T. Dean <[email protected]>
 * @package memcached-client
 */
class memcached
{
   // {{{ properties
   // {{{ public

   /**
    * Command statistics
    *
    * @var     array
    * @access  public
    */
   var $stats;
   
   // }}}
   // {{{ private

   /**
    * Cached Sockets that are connected
    *
    * @var     array
    * @access  private
    */
   var $_cache_sock;
   
   /**
    * Current debug status; 0 - none to 9 - profiling
    *
    * @var     boolean
    * @access  private
    */
   var $_debug;
   
   /**
    * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
    *
    * @var     array
    * @access  private
    */
   var $_host_dead;
   
   /**
    * Is compression available?
    *
    * @var     boolean
    * @access  private
    */
   var $_have_zlib;
   
   /**
    * Do we want to use compression?
    *
    * @var     boolean
    * @access  private
    */
   var $_compress_enable;
   
   /**
    * At how many bytes should we compress?
    *
    * @var     interger
    * @access  private
    */
   var $_compress_threshold;
   
   /**
    * Are we using persistant links?
    *
    * @var     boolean
    * @access  private
    */
   var $_persistant;
   
   /**
    * If only using one server; contains ip:port to connect to
    *
    * @var     string
    * @access  private
    */
   var $_single_sock;
   
   /**
    * Array containing ip:port or array(ip:port, weight)
    *
    * @var     array
    * @access  private
    */
   var $_servers;
   
   /**
    * Our bit buckets
    *
    * @var     array
    * @access  private
    */
   var $_buckets;
   
   /**
    * Total # of bit buckets we have
    *
    * @var     interger
    * @access  private
    */
   var $_bucketcount;
   
   /**
    * # of total servers we have
    *
    * @var     interger
    * @access  private
    */
   var $_active;

   // }}}
   // }}}
   // {{{ methods
   // {{{ public functions
   // {{{ memcached()

   /**
    * Memcache initializer
    *
    * @param   array    $args    Associative array of settings
    *
    * @return  mixed
    * @access  public
    */
   function memcached ($args)
   {
      $this->set_servers($args['servers']);
      $this->_debug = $args['debug'];
      $this->stats = array();
      $this->_compress_threshold = $args['compress_threshold'];
      $this->_persistant = isset($args['persistant']) ? $args['persistant'] : false;
      $this->_compress_enable = true;
      $this->_have_zlib = function_exists("gzcompress");
      
      $this->_cache_sock = array();
      $this->_host_dead = array();
   }

   // }}}
   // {{{ add()

   /**
    * Adds a key/value to the memcache server if one isn't already set with 
    * that key
    *
    * @param   string   $key     Key to set with data
    * @param   mixed    $val     Value to store
    * @param   interger $exp     (optional) Time to expire data at
    *
    * @return  boolean
    * @access  public
    */
   function add ($key, $val, $exp = 0)
   {
      return $this->_set('add', $key, $val, $exp);
   }

   // }}}
   // {{{ decr()

   /**
    * Decriment a value stored on the memcache server
    *
    * @param   string   $key     Key to decriment
    * @param   interger $amt     (optional) Amount to decriment
    *
    * @return  mixed    FALSE on failure, value on success
    * @access  public
    */
   function decr ($key, $amt=1)
   {
      return $this->_incrdecr('decr', $key, $amt);
   }

   // }}}
   // {{{ delete()

   /**
    * Deletes a key from the server, optionally after $time
    *
    * @param   string   $key     Key to delete
    * @param   interger $time    (optional) How long to wait before deleting
    *
    * @return  boolean  TRUE on success, FALSE on failure
    * @access  public
    */
   function delete ($key, $time = 0)
   {
      if (!$this->_active)
         return false;
         
      $sock = $this->get_sock($key);
      if (!is_resource($sock))
         return false;
      
      $key = is_array($key) ? $key[1] : $key;
      
      $this->stats['delete']++;
      $cmd = "delete $key $time\r\n";
      if(!fwrite($sock, $cmd, strlen($cmd)))
      {
         $this->_dead_sock($sock);
         return false;
      }
      $res = trim(fgets($sock));
      
      if ($this->_debug)
         printf("MemCache: delete %s (%s)\n", $key, $res);
      
      if ($res == "DELETED")
         return true;
      return false;
   }

   // }}}
   // {{{ disconnect_all()

   /**
    * Disconnects all connected sockets
    *
    * @access  public
    */
   function disconnect_all ()
   {
      foreach ($this->_cache_sock as $sock)
         fclose($sock);

      $this->_cache_sock = array();
   }

   // }}}
   // {{{ enable_compress()

   /**
    * Enable / Disable compression
    *
    * @param   boolean  $enable  TRUE to enable, FALSE to disable
    *
    * @access  public
    */
   function enable_compress ($enable)
   {
      $this->_compress_enable = $enable;
   }

   // }}}
   // {{{ forget_dead_hosts()

   /**
    * Forget about all of the dead hosts
    *
    * @access  public
    */
   function forget_dead_hosts ()
   {
      $this->_host_dead = array();
   }

   // }}}
   // {{{ get()

   /**
    * Retrieves the value associated with the key from the memcache server
    *
    * @param  string   $key     Key to retrieve
    *
    * @return  mixed
    * @access  public
    */
   function get ($key
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
php高并发下的抢购发布时间:2022-07-10
下一篇:
PHP将html内容转换为image图片发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap