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 简单数组排序实现代码
Aug 05 PHP
php中通过Ajax如何实现异步文件上传的代码实例
May 07 PHP
php学习笔记 php中面向对象三大特性之一[封装性]的应用
Jun 13 PHP
php eval函数用法总结
Oct 31 PHP
PHP中ob_start函数的使用说明
Nov 11 PHP
yii实现级联下拉菜单的方法
Jul 31 PHP
php自动更新版权信息显示的方法
Jun 19 PHP
php实现的单一入口应用程序实例分析
Sep 23 PHP
PHP目录与文件操作技巧总结(创建,删除,遍历,读写,修改等)
Sep 11 PHP
PHP使用curl_multi实现并发请求的方法示例
Apr 29 PHP
laravel 数据迁移与 Eloquent ORM的实现方法
Apr 12 PHP
PHP面向对象程序设计__tostring()和__invoke()用法分析
Jun 12 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
追忆往昔!浅谈收音机的百年发展历史
2021/03/01 无线电
phpMyAdmin 安装教程全攻略
2007/03/19 PHP
php 从数据库提取二进制图片的处理代码
2009/09/09 PHP
PhpMyAdmin出现export.php Missing parameter: what /export_type错误解决方法
2012/08/09 PHP
PHP获取数组中某元素的位置及array_keys函数应用
2013/01/29 PHP
php ZipArchive实现多文件打包下载实例
2019/10/31 PHP
JavaScript中void(0)的具体含义解释
2007/02/27 Javascript
Jquery替换已存在于element上的event的方法
2010/03/09 Javascript
JQuery AJAX提交中文乱码的解决方案
2010/07/02 Javascript
Javascript中的String对象详谈
2014/03/03 Javascript
IE6/IE7中JavaScript json提示缺少标识符、字符串或数字问题处理
2014/12/16 Javascript
JavaScript定时器和优化的取消定时器方法
2015/07/03 Javascript
jQuery过滤HTML标签并高亮显示关键字的方法
2015/08/07 Javascript
javascript中Date format(js日期格式化)方法小结
2015/12/17 Javascript
基于javascript实现全屏漂浮广告
2016/03/31 Javascript
javascript稀疏数组(sparse array)和密集数组用法分析
2016/12/28 Javascript
Angular项目中$scope.$apply()方法的使用详解
2017/07/26 Javascript
electron实现qq快捷登录的方法示例
2018/10/22 Javascript
python 写入csv乱码问题解决方法
2016/10/23 Python
Python复制Word内容并使用格式设字体与大小实例代码
2018/01/22 Python
python和flask中返回JSON数据的方法
2018/03/26 Python
django启动uwsgi报错的解决方法
2018/04/08 Python
详解Python3序列赋值、序列解包
2019/05/14 Python
解析Tensorflow之MNIST的使用
2020/06/30 Python
Python中flatten( ),matrix.A用法说明
2020/07/05 Python
Pycharm Git 设置方法
2020/09/15 Python
Python调用飞书发送消息的示例
2020/11/10 Python
Selenium 配置启动项参数的方法
2020/12/04 Python
CSS3 清除浮动的方法示例
2018/06/01 HTML / CSS
html5组织文档结构_动力节点Java学院整理
2017/07/11 HTML / CSS
优秀教师事迹简介
2014/02/02 职场文书
高中生第一学年自我鉴定
2014/09/12 职场文书
公司领导班子群众路线四风问题对照检查材料
2014/10/02 职场文书
手术室消毒隔离制度
2015/08/05 职场文书
python 实现德洛内三角剖分的操作
2021/04/22 Python
Golang并发操作中常见的读写锁详析
2021/08/30 Golang