Zend Framework实现将session存储在memcache中的方法


Posted in PHP onMarch 22, 2016

本文实例讲述了Zend Framework实现将session存储在memcache中的方法。分享给大家供大家参考,具体如下:

在zend framework中,已经可以将session存储在数据库中了,不过还不支持memcache,我简单得实现了一下。

下面是SaveHandler,文件名为 :Memcached.php ,将其放在 /Zend/Session/SaveHandler 目录下,代码如下(需要有php_memcache支持,因为字符长度限制,我把部分注释去掉了):

require_once 'Zend/Session.php';
require_once 'Zend/Config.php';
class Zend_Session_SaveHandler_Memcached implements Zend_Session_SaveHandler_Interface
{
  const LIFETIME     = 'lifetime';
  const OVERRIDE_LIFETIME = 'overrideLifetime';
  const MEMCACHED      = 'memcached';
  protected $_lifetime = false;
  protected $_overrideLifetime = false;
  protected $_sessionSavePath;
  protected $_sessionName;
  protected $_memcached;
  /**
   * Constructor
   *
   * $config is an instance of Zend_Config or an array of key/value pairs containing configuration options for
   * Zend_Session_SaveHandler_Memcached . These are the configuration options for
   * Zend_Session_SaveHandler_Memcached:
   *
   *
   *   sessionId    => The id of the current session
   *   sessionName   => The name of the current session
   *   sessionSavePath => The save path of the current session
   *
   * modified      => (string) Session last modification time column
   *
   * lifetime     => (integer) Session lifetime (optional; default: ini_get('session.gc_maxlifetime'))
   *
   * overrideLifetime => (boolean) Whether or not the lifetime of an existing session should be overridden
   *   (optional; default: false)
   *
   * @param Zend_Config|array $config   User-provided configuration
   * @return void
   * @throws Zend_Session_SaveHandler_Exception
   */
  public function __construct($config)
  {
    if ($config instanceof Zend_Config) {
      $config = $config->toArray();
    } else if (!is_array($config)) {
      /**
       * @see Zend_Session_SaveHandler_Exception
       */
      require_once 'Zend/Session/SaveHandler/Exception.php';
      throw new Zend_Session_SaveHandler_Exception(
        '$config must be an instance of Zend_Config or array of key/value pairs containing '
       . 'configuration options for Zend_Session_SaveHandler_Memcached .');
    }
    foreach ($config as $key => $value) {
      do {
        switch ($key) {
          case self::MEMCACHED:
            $this->createMemcached($value);
            break;
          case self::LIFETIME:
            $this->setLifetime($value);
            break;
          case self::OVERRIDE_LIFETIME:
            $this->setOverrideLifetime($value);
            break;
          default:
            // unrecognized options passed to parent::__construct()
            break 2;
        }
        unset($config[$key]);
      } while (false);
    }
  }
  /**
   * 创建memcached连接对象
   *
   * @return void
   */
  public function createMemcached($config){
   $mc = new Memcache;
   foreach ($config as $value){
    $mc->addServer($value['ip'], $value['port']);
   }
   $this->_memcached = $mc;
  }
  public function __destruct()
  {
    Zend_Session::writeClose();
  }
  /**
   * Set session lifetime and optional whether or not the lifetime of an existing session should be overridden
   *
   * $lifetime === false resets lifetime to session.gc_maxlifetime
   *
   * @param int $lifetime
   * @param boolean $overrideLifetime (optional)
   * @return Zend_Session_SaveHandler_Memcached
   */
  public function setLifetime($lifetime, $overrideLifetime = null)
  {
    if ($lifetime < 0) {
      /**
       * @see Zend_Session_SaveHandler_Exception
       */
      require_once 'Zend/Session/SaveHandler/Exception.php';
      throw new Zend_Session_SaveHandler_Exception();
    } else if (empty($lifetime)) {
      $this->_lifetime = (int) ini_get('session.gc_maxlifetime');
    } else {
      $this->_lifetime = (int) $lifetime;
    }
    if ($overrideLifetime != null) {
      $this->setOverrideLifetime($overrideLifetime);
    }
    return $this;
  }
  /**
   * Retrieve session lifetime
   *
   * @return int
   */
  public function getLifetime()
  {
    return $this->_lifetime;
  }
  /**
   * Set whether or not the lifetime of an existing session should be overridden
   *
   * @param boolean $overrideLifetime
   * @return Zend_Session_SaveHandler_Memcached
   */
  public function setOverrideLifetime($overrideLifetime)
  {
    $this->_overrideLifetime = (boolean) $overrideLifetime;
    return $this;
  }
  public function getOverrideLifetime()
  {
    return $this->_overrideLifetime;
  }
  /**
   * Retrieve session lifetime considering
   *
   * @param array $value
   * @return int
   */
  public function open($save_path, $name)
  {
    $this->_sessionSavePath = $save_path;
    $this->_sessionName   = $name;
    return true;
  }
  /**
   * Retrieve session expiration time
   *
   * @param * @param array $value
   * @return int
   */
  public function close()
  {
    return true;
  }
  public function read($id)
  {
    $return = '';
    $value = $this->_memcached->get($id); //获取数据
    if ($value) {
      if ($this->_getExpirationTime($value) > time()) {
        $return = $value['data'];
      } else {
        $this->destroy($id);
      }
    }
    return $return;
  }
  public function write($id, $data)
  {
    $return = false;
    $insertDate = array('modified' => time(),
               'data'   => (string) $data);
      $value = $this->_memcached->get($id); //获取数据
    if ($value) {
      $insertDate['lifetime'] = $this->_getLifetime($value);
      if ($this->_memcached->replace($id,$insertDate)) {
        $return = true;
      }
    } else {
      $insertDate['lifetime'] = $this->_lifetime;
      if ($this->_memcached->add($id, $insertDate,false,$this->_lifetime)) {
        $return = true;
      }
    }
    return $return;
  }
  public function destroy($id)
  {
    $return = false;
    if ($this->_memcached->delete($id)) {
      $return = true;
    }
    return $return;
  }
  public function gc($maxlifetime)
  {
    return true;
  }
  protected function _getLifetime($value)
  {
    $return = $this->_lifetime;
    if (!$this->_overrideLifetime) {
      $return = (int) $value['lifetime'];
    }
    return $return;
  }
  protected function _getExpirationTime($value)
  {
    return (int) $value['modified'] + $this->_getLifetime($value);
  }
}

配置(可以添加多台memcache服务器,做分布式):

$config = array(
  'memcached'=> array(
    array(
      'ip'=>'192.168.0.1',
      'port'=>11211
    )
  ),
  'lifetime' =>123334
);
//create your Zend_Session_SaveHandler_DbTable and
//set the save handler for Zend_Session
Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_Memcached($config));
//start your session!
Zend_Session::start();

配置好后,session的使用方法和以前一样,不用管底层是怎么实现的!

希望本文所述对大家基于Zend Framework框架的PHP程序设计有所帮助。

PHP 相关文章推荐
php 向访客和爬虫显示不同的内容
Nov 09 PHP
PHP mcrypt可逆加密算法分析
Jul 19 PHP
采集邮箱的php代码(抓取网页中的邮箱地址)
Jul 17 PHP
PHP实现图片裁剪、添加水印效果代码
Oct 01 PHP
PHP封装分页函数实现文本分页和数字分页
Oct 23 PHP
PHP利用header跳转失效的解决方法
Oct 24 PHP
thinkphp模板输出技巧汇总
Nov 24 PHP
php判断当前操作系统类型
Oct 28 PHP
利用PHP自动生成印有用户信息的名片
Aug 01 PHP
利用PHP生成静态html页面的原理
Sep 30 PHP
CI框架网页缓存简单用法分析
Dec 26 PHP
PHP去除空数组且数组键名重置的讲解
Feb 28 PHP
Zend Framework分页类用法详解
Mar 22 #PHP
Zend Framework生成验证码并实现验证码验证功能(附demo源码下载)
Mar 22 #PHP
PHP的Laravel框架中使用AdminLTE模板来编写网站后台界面
Mar 21 #PHP
深入解析PHP的Laravel框架中的event事件操作
Mar 21 #PHP
Android App中DrawerLayout抽屉效果的菜单编写实例
Mar 21 #PHP
PHP的Laravel框架结合MySQL与Redis数据库的使用部署
Mar 21 #PHP
PHP编写学校网站上新生注册登陆程序的实例分享
Mar 21 #PHP
You might like
PHP4 与 MySQL 数据库操作函数详解
2006/12/06 PHP
Windows PHP5和Apache的安装与配置
2009/06/08 PHP
php防攻击代码升级版
2010/12/29 PHP
php接口与接口引用的深入解析
2013/08/09 PHP
WordPress开发中自定义菜单的相关PHP函数使用简介
2016/01/05 PHP
php获取访问者浏览页面的浏览器类型
2017/01/23 PHP
extjs form textfield的隐藏方法
2008/12/29 Javascript
jquery获得下拉框值的代码
2011/08/13 Javascript
js获取鼠标点击的对象,点击另一个按钮删除该对象的实现代码
2016/05/13 Javascript
nodejs后台集成ueditor富文本编辑器的实例
2017/07/11 NodeJs
基于react组件之间的参数传递(详解)
2017/09/05 Javascript
vue2.0 + element UI 中 el-table 数据导出Excel的方法
2018/03/02 Javascript
vue 中基于html5 drag drap的拖放效果案例分析
2018/11/01 Javascript
微信实现自动跳转到用其他浏览器打开指定APP下载
2019/02/15 Javascript
layer.js open 隐藏滚动条的例子
2019/09/05 Javascript
vue配置nprogress实现页面顶部进度条
2019/09/21 Javascript
Vue中实现回车键切换焦点的方法
2020/02/19 Javascript
《javascript设计模式》学习笔记四:Javascript面向对象程序设计链式调用实例分析
2020/04/07 Javascript
Vue实现跑马灯效果
2020/05/25 Javascript
Vue自定义多选组件使用详解
2020/09/08 Javascript
浅析Python中将单词首字母大写的capitalize()方法
2015/05/18 Python
wxPython中listbox用法实例详解
2015/06/01 Python
快速入手Python字符编码
2016/08/03 Python
Python根据已知邻接矩阵绘制无向图操作示例
2018/06/23 Python
Django后端接收嵌套Json数据及解析详解
2019/07/17 Python
Python 取numpy数组的某几行某几列方法
2019/10/24 Python
Python内置加密模块用法解析
2019/11/25 Python
Python itertools.product方法代码实例
2020/03/27 Python
Python3+selenium配置常见报错解决方案
2020/08/28 Python
浅谈CSS3特性查询(Feature Query: @supports)功能简介
2017/07/31 HTML / CSS
施华洛世奇韩国官网:SWAROVSKI韩国
2018/06/05 全球购物
.net面试题
2016/09/17 面试题
什么是就业协议书
2014/04/17 职场文书
认真学习保证书
2015/02/26 职场文书
javascript条件式访问属性和箭头函数介绍
2021/11/17 Javascript
SQL Server2019安装的详细步骤实战记录(亲测可用)
2022/06/10 SQL Server