Zend Framework实现将session存储在memcache中的方法,zendmemcache
Zend Framework实现将session存储在memcache中的方法,zendmemcache
本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Zend Framework框架的PHP程序设计有所帮助。
您可能感兴趣的文章:
- Zend Framework框架教程之Zend_Db_Table_Rowset用法实例分析
- Zend Framework教程之Zend_Db_Table_Row用法实例分析
- Zend Framework教程之Zend_Db_Table用法详解
- Zend Framework教程之Zend_Form组件实现表单提交并显示错误提示的方法
- Zend Framework开发入门经典教程
- Zend Framework框架Smarty扩展实现方法
- Zend Framework框架路由机制代码分析
- Zend Framework实现具有基本功能的留言本(附demo源码下载)
- Zend Framework分页类用法详解
- Zend Framework实现多文件上传功能实例
- Zend Framework入门之环境配置及第一个Hello World示例(附demo源码下载)
- Zend Framework教程之连接数据库并执行增删查的方法(附demo源码下载)
- Zend Framework教程之Zend_Db_Table表关联实例详解

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











세션 실패는 일반적으로 세션 수명 만료 또는 서버 종료로 인해 발생합니다. 해결 방법은 다음과 같습니다. 1. 세션 수명을 연장합니다. 3. 쿠키를 사용합니다. 4. 세션 관리 미들웨어를 사용합니다.

PHPSession의 도메인 간 문제 해결 프런트엔드와 백엔드 분리 개발에서 도메인 간 요청이 표준이 되었습니다. 도메인 간 문제를 처리할 때 일반적으로 세션 사용 및 관리가 포함됩니다. 그러나 브라우저 원본 정책 제한으로 인해 기본적으로 도메인 간에 세션을 공유할 수 없습니다. 이 문제를 해결하려면 도메인 간 세션 공유를 달성하기 위한 몇 가지 기술과 방법을 사용해야 합니다. 1. 도메인 간 세션을 공유하기 위한 쿠키의 가장 일반적인 사용

웹 개발에서는 웹사이트 성능과 응답 속도를 향상시키기 위해 캐싱 기술을 사용해야 하는 경우가 많습니다. Memcache는 모든 데이터 유형을 캐시할 수 있고 높은 동시성 및 고가용성을 지원하는 널리 사용되는 캐싱 기술입니다. 이 기사에서는 PHP 개발에 Memcache를 사용하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. Memcache 설치 Memcache를 사용하려면 먼저 서버에 Memcache 확장 프로그램을 설치해야 합니다. CentOS 운영 체제에서는 다음 명령을 사용할 수 있습니다.

JavaScript쿠키 JavaScript 쿠키를 사용하는 것은 선호도, 구매, 커미션 및 기타 정보를 기억하고 추적하는 가장 효과적인 방법입니다. 더 나은 방문자 경험이나 웹사이트 통계를 위해 필요한 정보입니다. PHPCookieCookies는 클라이언트 컴퓨터에 저장되고 추적 목적으로 보관되는 텍스트 파일입니다. PHP는 HTTP 쿠키를 투명하게 지원합니다. JavaScript 쿠키는 어떻게 작동하나요? 귀하의 서버는 쿠키 형태로 방문자의 브라우저에 일부 데이터를 보냅니다. 브라우저는 쿠키를 허용할 수 있습니다. 존재하는 경우 방문자의 하드 드라이브에 일반 텍스트 기록으로 저장됩니다. 이제 방문자가 사이트의 다른 페이지에 도달하면

Zend Framework에서 권한 제어를 위해 ACL(AccessControlList)을 사용하는 방법 소개: 웹 애플리케이션에서 권한 제어는 중요한 기능입니다. 이는 사용자가 액세스 권한이 있는 페이지와 기능에만 액세스할 수 있도록 하고 무단 액세스를 방지합니다. Zend 프레임워크는 ACL(AccessControlList) 구성 요소를 사용하여 권한 제어를 구현하는 편리한 방법을 제공합니다. 이 기사에서는 Zend Framework에서 ACL을 사용하는 방법을 소개합니다.

도메인 간 PHPSession과 AJAX 간의 비동기 통신 최적화 인터넷이 발전하면서 도메인 간 액세스 및 비동기 통신이 현대 웹 애플리케이션 개발에서 일반적인 요구 사항이 되었습니다. 이 기사에서는 PHPSession을 사용하여 도메인 간 액세스를 달성하는 방법에 중점을 두고 AJAX의 비동기 통신 효율성을 향상시키는 몇 가지 최적화 방법을 제공합니다. 1. 크로스 도메인 액세스 문제 웹 개발에서 브라우저가 한 도메인 이름의 웹 페이지에서 HTTP 요청을 시작한 다음 다른 도메인 이름에 속한 응답 데이터를 반환하는 경우 발생합니다.

12월 9일 뉴스에 따르면 Cooler Master는 최근 타이페이 컴퓨트 쇼(Taipei Compute Show)의 시연 행사에서 노트북 모듈 솔루션 제공업체인 Framework와 협력하여 미니 섀시 키트를 시연했습니다. 프레임워크 노트북에서. 현재 이 제품은 시중에 판매되기 시작했으며 가격은 39달러로 현재 환율로 약 279위안(한화 약 279위안)에 해당한다. 이 섀시 키트의 모델 번호는 "frameWORKMAINBOARDCASE"로 명명됩니다. 디자인 측면에서는 297x133x15mm 크기로 최고의 컴팩트함과 실용성을 구현합니다. 원래 디자인은 프레임워크 노트북에 원활하게 연결할 수 있도록 하는 것입니다.

세션 실패 이유에는 세션 시간 초과, 세션 수 제한, 세션 무결성 검사, 서버 다시 시작, 브라우저 또는 장치 문제 등이 포함됩니다. 자세한 소개: 1. 세션 시간 초과: 서버는 사용자가 일정 기간 동안 서버와 상호 작용하지 않으면 세션에 대한 기본 시간 초과를 설정합니다. 2. 세션 번호 제한: 서버에는 숫자가 있습니다. 각 사용자에 대한 세션 수 제한이 설정됩니다. 사용자가 생성한 세션 수가 이 제한을 초과하면 최신 세션이 가장 오래된 세션을 덮어쓰게 됩니다.
