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_SELF的安全问题
Sep 05 PHP
php 日期时间处理函数小结
Dec 18 PHP
php中使用Curl、socket、file_get_contents三种方法POST提交数据
Aug 12 PHP
实测在class的function中include的文件中非php的global全局环境
Jul 15 PHP
PHP set_error_handler()函数使用详解(示例)
Nov 12 PHP
PHP+jQuery 注册模块的改进(一):验证码存入SESSION
Oct 14 PHP
php为字符串前后添加指定数量字符的方法
May 04 PHP
PHP is_array() 检测变量是否是数组的实现方法
Jun 13 PHP
PHP实现自动识别原编码并对字符串进行编码转换的方法
Jul 13 PHP
谈谈从phpinfo中能获取哪些值得注意的信息
Mar 28 PHP
ThinkPHP删除栏目(实现批量删除栏目)
Jun 21 PHP
php使用环形链表解决约瑟夫问题完整示例
Aug 07 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 Socket 编程模拟Http post和get请求
2014/11/25 PHP
PHP模板引擎Smarty内建函数foreach,foreachelse用法分析
2016/04/11 PHP
Yii2简单实现给表单添加验证码的方法
2016/07/18 PHP
通过php动态传数据到highcharts
2017/04/05 PHP
PHP匿名函数(闭包函数)详解
2019/03/22 PHP
PHP操作路由器实现方法示例
2019/04/27 PHP
PHP如何使用JWT做Api接口身份认证的实现
2020/02/03 PHP
Prototype Object对象 学习
2009/07/12 Javascript
jquery如何改变html标签的样式(两种实现方法)
2013/01/16 Javascript
jquery遍历数组与筛选数组的方法
2013/11/05 Javascript
Firefox中通过JavaScript复制数据到剪贴板(Copy to Clipboard 跨浏览器版)
2013/11/22 Javascript
用js+iframe形成页面的一种遮罩效果的具体实现
2013/12/31 Javascript
javascript中定义私有方法说明(private method)
2014/01/27 Javascript
JS动态添加Table的TR,TD实现方法
2015/01/28 Javascript
jQuery实现三级菜单的代码
2016/05/09 Javascript
微信小程序 简单DEMO布局,逻辑,样式的练习
2016/11/30 Javascript
JavaScript函数节流的两种写法
2017/04/07 Javascript
详解React-Native解决键盘遮挡问题(Keyboard遮挡问题)
2017/07/13 Javascript
bootstrap datepicker插件默认英文修改为中文
2017/07/28 Javascript
详解webpack4多入口、多页面项目构建案例
2018/05/25 Javascript
详解Webpack多环境代码打包的方法
2018/08/03 Javascript
详解Python迭代和迭代器
2016/03/28 Python
Python获取文件所在目录和文件名的方法
2017/01/12 Python
python消除序列的重复值并保持顺序不变的实例
2018/11/08 Python
python linecache 处理固定格式文本数据的方法
2019/01/08 Python
pandas DataFrame索引行列的实现
2019/06/04 Python
django 中使用DateTime常用的时间查询方式
2019/12/03 Python
基于django 的orm中非主键自增的实现方式
2020/05/18 Python
python 使用xlsxwriter循环向excel中插入数据和图片的操作
2021/01/01 Python
AmazeUI 手机版页面的顶部导航条Header与侧边导航栏offCanvas的示例代码
2020/08/19 HTML / CSS
德国箱包网上商店:koffer24.de
2016/07/27 全球购物
高中政治教学反思
2014/01/18 职场文书
军训感想500字
2014/02/20 职场文书
家长对孩子的寒假评语
2015/10/09 职场文书
Django如何创作一个简单的最小程序
2021/05/12 Python
Python音乐爬虫完美绕过反爬
2021/08/30 Python