当前位置: 首页 > 编程文章 >

Zend Framework 实现 Session 存储至 Memcached 的方法

Zend Framework 实现 Session 存储至 Memcached 的方法

作者:林禾时间:2025-05-01 09:07:24浏览:759

本文介绍如何在 Zend Framework 中通过自定义 SaveHandler 将 Session 数据存储在 Memcached 中。由于原生不支持,需创建继承 Zend_Session_SaveHandler_Interface 的类并配置服务器参数,之后即可像往常一样使用 Session,底层自动切换存储介质。

本文目录展开

Zend Framework 集成 Memcached 存储 Session

本示例演示了如何在 Zend Framework 中将 Session 数据存储到 Memcached 缓存服务中,供开发者参考实践。

虽然 Zend Framework 原生支持将 Session 持久化到数据库,但并未内置对 Memcached 的支持。此处提供了一种简单的扩展方案来实现该功能。

核心实现为自定义 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);
  }
}

在使用前需进行相应配置,支持添加多台 Memcached 服务器以构建分布式集群环境。


$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 程序设计技巧。

上一篇
Yii框架关联查询with用法详解

本文详细解析Yii框架中with关联查询的四种核心关系类型:BELONGS_TO、HAS_MANY、HAS_ONE和MANY_MANY。通过用户与博客表的实例,直观展示各关系的定义方式与适用场景,并补充select、condition等高级配置选项以及group、having等延迟加载参数,帮助开发者快速掌握复杂数据关联查询技巧。

下一篇
PHP集成百度AI OCR实现图片文字识别教程

本文介绍如何在PHP项目中集成百度AI OCR服务以实现图片文字识别功能。首先需在百度AI开放平台注册并获取AppID、API Key和Secret Key三个关键凭证。接着通过GitHub或官网下载OCR SDK,配置好密钥后运行DemoAipOcr.php示例文件即可测试。若遇到getimagesizefromstring函数未定义错误,需确保PHP版本不低于5.4.0。

相关文章

更多
PHP 集成 Memcached 实现高性能缓存与 Session 共享

Memcached 是一款高效快速的分布式内存对象缓存系统,主要用于加速 Web 动态应用程序。本文介绍了 Memcached 1.1.12 版本的安装步骤及守护进程运行参数,并详细阐述了在 PHP 中通过 memcached-client.php 库进行对象存取的具体方法。此外,文章还展示了如何利用 Memcached 优化高并发场景下的 Session 存储,有效降低数据库负载并提升脚本执行速度。

2025.07.01 972
Nginx HttpMemcModule与直接访问Memcached效率对比测试

通过ab工具对Nginx HttpMemcModule代理方式与PHP直接连接Memcached方式进行并发测试。初始测试显示两者效率接近,但直接连接失败率较高。调整内核TCP参数后,HttpMemcModule平均效率降至NativeMC的72.62%,但Failed requests降为0。鉴于连接复用优势及透明性,该方案仍具可用性。

2025.06.06 995
PHP Memcached 高级缓存配置图文教程

Memcached 作为高性能分布式内存对象缓存系统,能有效缓解数据库压力。本文详细讲解在 Windows 环境下安装 Memcached 服务、通过 Telnet 验证连接,以及在 PHP 中配置 php_memcache.dll 扩展并启用缓存功能的完整步骤。

2025.12.12 981
PHP扩展memcached与memcache安装配置指南

本文介绍在PHP环境中安装memcache和memcached两个缓存扩展的具体方法。memcache为底层开发库,memcached基于libmemcached构建且较新。通过编译源码并配置php.ini加载.so文件,可实现PHP对缓存数据的读写,从而缓存执行结果以提升性能。

2026.03.30 976
Nginx upstream模块原理与Memcached实现解析

Nginx的upstream模块使服务器具备跨越单机的横向处理能力,通过接收、处理和转发网络数据构建应用级拆分。该模块本质属于handler,不产生内容而是获取后端响应,核心在于配置若干回调函数以构造请求和解析响应。本文以ngx_http_memcached模块为例,详细拆解其创建数据结构、设置后端列表、初始化环境等六个固定流程,并深入分析create_request、process_header等关键回调函数的具体实现逻辑。

2026.05.30 959
Java集成Memcached:安装、配置与Spymemcached客户端使用指南

Memcached是一款广泛使用的高并发内存缓存系统。本文介绍在Ubuntu环境下通过apt-get安装及启动Memcached的方法,包括端口和内存参数的配置。重点讲解如何在Java项目中引入spymemcached依赖,并通过MemcachedClient实现数据的存取操作。同时提供简单的监控命令以观察运行状态,并指出高并发场景下可能出现的超时问题。

2026.02.18 958

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。