当前位置: 移动技术网 > IT编程>开发语言>PHP > Zend Framework实现将session存储在memcache中的方法

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网