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 相关文章推荐
ASP知识讲座四
Oct 09 PHP
PHP程序员面试 切忌急功近利(更需要注重以后的发展)
Sep 01 PHP
PHP常用特殊运算符号和函数总结(php新手入门必看)
Feb 02 PHP
解决PHP超大文件下载,断点续传下载的方法详解
Jun 06 PHP
php堆排序(heapsort)练习
Nov 13 PHP
Discuz批量替换帖子内容的方法(使用SQL更新数据库)
Jun 23 PHP
PHP微信开发之查询微信精选文章
Jun 23 PHP
php flush无效,IIS7下php实时输出的方法
Aug 25 PHP
实例讲解YII2中多表关联的使用方法
Jul 21 PHP
PHP编程实现微信企业向用户付款的方法示例
Jul 26 PHP
Laravel如何自定义command命令浅析
Mar 23 PHP
Laravel基础-关于引入公共文件的两种方式
Oct 18 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
php生成的html meta和link标记在body标签里 顶部有个空行
2010/05/18 PHP
浅谈ThinkPHP的URL重写
2014/11/25 PHP
分享一则PHP定义函数代码
2015/02/26 PHP
详解WordPress开发中过滤属性以及Sql语句的函数使用
2015/12/25 PHP
php 7新特性之类型申明详解
2017/06/06 PHP
JavaScript搜索字符串并将搜索结果返回到字符串的方法
2015/04/06 Javascript
纯javascript实现四方向文本无缝滚动效果
2015/06/16 Javascript
JavaScript实现带缓冲效果的随屏滚动漂浮广告代码
2015/11/06 Javascript
jQuery实现立体式数字动态增加(animate方法)
2016/12/21 Javascript
Angular2使用jQuery的方法教程
2017/05/28 jQuery
jQuery中extend函数简单用法示例
2017/10/11 jQuery
JavaScript实现快速排序的方法分析
2018/01/10 Javascript
vue实现密码显示隐藏切换功能
2018/02/23 Javascript
快速解决Vue项目在IE浏览器中显示空白的问题
2018/09/04 Javascript
浅谈angular2子组件的事件传递(任意组件事件传递)
2018/09/30 Javascript
javascript设计模式 ? 迭代器模式原理与用法实例分析
2020/04/17 Javascript
Vue 使用iframe引用html页面实现vue和html页面方法的调用操作
2020/11/16 Javascript
Python实现字典依据value排序
2016/02/24 Python
python 巧用正则寻找字符串中的特定字符的位置方法
2018/05/02 Python
Python闭包思想与用法浅析
2018/12/27 Python
python支付宝支付示例详解
2019/08/22 Python
Python3开发环境搭建详细教程
2020/06/18 Python
HTML5和CSS3实例教程总结(推荐)
2016/07/18 HTML / CSS
澳大利亚最超值的自行车之家:Reid Cycles
2019/03/24 全球购物
维多利亚的秘密阿联酋官网:Victoria’s Secret阿联酋
2019/12/07 全球购物
打造完美自荐信
2014/01/24 职场文书
爱情保证书范文
2014/02/01 职场文书
医院安全生产月活动总结
2014/07/05 职场文书
大学生村官个人总结
2015/02/15 职场文书
2015年家长学校工作总结
2015/04/22 职场文书
详解如何修改nginx的默认端口
2021/03/31 Servers
详解MySQL的Seconds_Behind_Master
2021/05/18 MySQL
详解CSS不定宽溢出文本适配滚动
2021/05/24 HTML / CSS
使用tensorflow 实现反向传播求导
2021/05/26 Python
MySQL表类型 存储引擎 的选择
2021/11/11 MySQL
GO语言异常处理分析 err接口及defer延迟
2022/04/14 Golang