A-A+

Zend Framework实现将session存储在memcache中的方法

2021年07月21日 我爱编程 暂无评论

这篇文章主要介绍了Zend Framework实现将session存储在memcache中的方法,结合实例形式分析了Zend Framework框架下将session存储在memcache的实现技巧,需要的朋友可以参考下。

本文实例讲述了Zend Framework实现将session存储在memcache中的方法,分享给大家供大家参考,具体如下:

在zend framework中,已经可以将session存储在数据库中了,不过还不支持memcache,我简单得实现了一下。

下面是SaveHandler,文件名为 :Memcached.php ,将其放在 /Zend/Session/SaveHandler 目录下,代码如下(需要有php_memcache支持,因为字符长度限制,我把部分注释去掉了):

  1. require_once 'Zend/Session.php';
  2. require_once 'Zend/Config.php';
  3. class Zend_Session_SaveHandler_Memcached implements Zend_Session_SaveHandler_Interface
  4. {
  5.   const LIFETIME     = 'lifetime';
  6.   const OVERRIDE_LIFETIME = 'overrideLifetime';
  7.   const MEMCACHED      = 'memcached';
  8.   protected $_lifetime = false;
  9.   protected $_overrideLifetime = false;
  10.   protected $_sessionSavePath;
  11.   protected $_sessionName;
  12.   protected $_memcached;
  13.   /**
  14.    * Constructor
  15.    *
  16.    * $config is an instance of Zend_Config or an array of key/value pairs containing configuration options for
  17.    * Zend_Session_SaveHandler_Memcached . These are the configuration options for
  18.    * Zend_Session_SaveHandler_Memcached:
  19.    *
  20.    *
  21.    *   sessionId    => The id of the current session
  22.    *   sessionName   => The name of the current session
  23.    *   sessionSavePath => The save path of the current session
  24.    *
  25.    * modified      => (string) Session last modification time column
  26.    *
  27.    * lifetime     => (integer) Session lifetime (optional; default: ini_get('session.gc_maxlifetime'))
  28.    *
  29.    * overrideLifetime => (boolean) Whether or not the lifetime of an existing session should be overridden
  30.    *   (optional; default: false)
  31.    *
  32.    * @param Zend_Config|array $config   User-provided configuration
  33.    * @return void
  34.    * @throws Zend_Session_SaveHandler_Exception
  35.    */
  36.   public function __construct($config)
  37.   {
  38.     if ($config instanceof Zend_Config) {
  39.       $config = $config->toArray();
  40.     } else if (!is_array($config)) {
  41.       /**
  42.        * @see Zend_Session_SaveHandler_Exception
  43.        */
  44.       require_once 'Zend/Session/SaveHandler/Exception.php';
  45.       throw new Zend_Session_SaveHandler_Exception(
  46.         '$config must be an instance of Zend_Config or array of key/value pairs containing '
  47.        . 'configuration options for Zend_Session_SaveHandler_Memcached .');
  48.     }
  49.     foreach ($config as $key => $value) {
  50.       do {
  51.         switch ($key) {
  52.           case self::MEMCACHED:
  53.             $this->createMemcached($value);
  54.             break;
  55.           case self::LIFETIME:
  56.             $this->setLifetime($value);
  57.             break;
  58.           case self::OVERRIDE_LIFETIME:
  59.             $this->setOverrideLifetime($value);
  60.             break;
  61.           default:
  62.             // unrecognized options passed to parent::__construct()
  63.             break 2;
  64.         }
  65.         unset($config[$key]);
  66.       } while (false);
  67.     }
  68.   }
  69.   /**
  70.    * 创建memcached连接对象
  71.    *
  72.    * @return void
  73.    */
  74.   public function createMemcached($config){
  75.    $mc = new Memcache;
  76.    foreach ($config as $value){
  77.     $mc->addServer($value['ip'], $value['port']);
  78.    }
  79.    $this->_memcached = $mc;
  80.   }
  81.   public function __destruct()
  82.   {
  83.     Zend_Session::writeClose();
  84.   }
  85.   /**
  86.    * Set session lifetime and optional whether or not the lifetime of an existing session should be overridden
  87.    *
  88.    * $lifetime === false resets lifetime to session.gc_maxlifetime
  89.    *
  90.    * @param int $lifetime
  91.    * @param boolean $overrideLifetime (optional)
  92.    * @return Zend_Session_SaveHandler_Memcached
  93.    */
  94.   public function setLifetime($lifetime$overrideLifetime = null)
  95.   {
  96.     if ($lifetime < 0) {
  97.       /**
  98.        * @see Zend_Session_SaveHandler_Exception
  99.        */
  100.       require_once 'Zend/Session/SaveHandler/Exception.php';
  101.       throw new Zend_Session_SaveHandler_Exception();
  102.     } else if (emptyempty($lifetime)) {
  103.       $this->_lifetime = (int) ini_get('session.gc_maxlifetime');
  104.     } else {
  105.       $this->_lifetime = (int) $lifetime;
  106.     }
  107.     if ($overrideLifetime != null) {
  108.       $this->setOverrideLifetime($overrideLifetime);
  109.     }
  110.     return $this;
  111.   }
  112.   /**
  113.    * Retrieve session lifetime
  114.    *
  115.    * @return int
  116.    */
  117.   public function getLifetime()
  118.   {
  119.     return $this->_lifetime;
  120.   }
  121.   /**
  122.    * Set whether or not the lifetime of an existing session should be overridden
  123.    *
  124.    * @param boolean $overrideLifetime
  125.    * @return Zend_Session_SaveHandler_Memcached
  126.    */
  127.   public function setOverrideLifetime($overrideLifetime)
  128.   {
  129.     $this->_overrideLifetime = (boolean) $overrideLifetime;
  130.     return $this;
  131.   }
  132.   public function getOverrideLifetime()
  133.   {
  134.     return $this->_overrideLifetime;
  135.   }
  136.   /**
  137.    * Retrieve session lifetime considering
  138.    *
  139.    * @param array $value
  140.    * @return int
  141.    */
  142.   public function open($save_path$name)
  143.   {
  144.     $this->_sessionSavePath = $save_path;
  145.     $this->_sessionName   = $name;
  146.     return true;
  147.   }
  148.   /**
  149.    * Retrieve session expiration time
  150.    *
  151.    * @param * @param array $value
  152.    * @return int
  153.    */
  154.   public function close()
  155.   {
  156.     return true;
  157.   }
  158.   public function read($id)
  159.   {
  160.     $return = '';
  161.     $value = $this->_memcached->get($id); //获取数据
  162.     if ($value) {
  163.       if ($this->_getExpirationTime($value) > time()) {
  164.         $return = $value['data'];
  165.       } else {
  166.         $this->destroy($id);
  167.       }
  168.     }
  169.     return $return;
  170.   }
  171.   public function write($id$data)
  172.   {
  173.     $return = false;
  174.     $insertDate = array('modified' => time(),
  175.                'data'   => (string) $data);
  176.       $value = $this->_memcached->get($id); //获取数据
  177.     if ($value) {
  178.       $insertDate['lifetime'] = $this->_getLifetime($value);
  179.       if ($this->_memcached->replace($id,$insertDate)) {
  180.         $return = true;
  181.       }
  182.     } else {
  183.       $insertDate['lifetime'] = $this->_lifetime;
  184.       if ($this->_memcached->add($id$insertDate,false,$this->_lifetime)) {
  185.         $return = true;
  186.       }
  187.     }
  188.     return $return;
  189.   }
  190.   public function destroy($id)
  191.   {
  192.     $return = false;
  193.     if ($this->_memcached->delete($id)) {
  194.       $return = true;
  195.     }
  196.     return $return;
  197.   }
  198.   public function gc($maxlifetime)
  199.   {
  200.     return true;
  201.   }
  202.   protected function _getLifetime($value)
  203.   {
  204.     $return = $this->_lifetime;
  205.     if (!$this->_overrideLifetime) {
  206.       $return = (int) $value['lifetime'];
  207.     }
  208.     return $return;
  209.   }
  210.   protected function _getExpirationTime($value)
  211.   {
  212.     return (int) $value['modified'] + $this->_getLifetime($value);
  213.   }
  214. }

配置(可以添加多台memcache服务器,做分布式):

  1. $config = array(
  2.   'memcached'=> array(
  3.     array(
  4.       'ip'=>'192.168.0.1',
  5.       'port'=>11211
  6.     )
  7.   ),
  8.   'lifetime' =>123334
  9. );
  10. //create your Zend_Session_SaveHandler_DbTable and
  11. //set the save handler for Zend_Session
  12. Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_Memcached($config));
  13. //start your session!
  14. Zend_Session::start();

配置好后,session的使用方法和以前一样,不用管底层是怎么实现的!

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录