Zend Framework implementation _php instance of a method stored in Memcache

Source: Internet
Author: User
Tags memcached zend zend framework

The example in this article describes the method that the Zend framework implements to store the session in Memcache. Share to everyone for your reference, specific as follows:

In the Zend Framework, the session can already be stored in the database, but it does not support memcache, I simply have to implement it.

The following is Savehandler, the file name is: memcached.php, put it in the/zend/session/savehandler directory, the code is as follows (need to have php_memcache support, because of the character length limit, I removed some of the comments):

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 a instance of Zend_config or an array of key/value pairs containing Configurati On the options for * zend_session_savehandler_memcached. These are the configuration options for * zend_session_savehandler_memcached: * * * sessionId => the I D 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 * * Lifetim e => (integer)Session lifetime (optional default:ini_get (' Session.gc_maxlifetime ')) * Overridelifetime => (Boolean) Whether Or not the lifetime of a existing session should is overridden * (optional; default:false) * * @param zend_c
  Onfig|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 is an instance of Zend_config or array of Key/value PA IRS 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); /** * Create memcached Connection object * * @return void */Public Function creatememcached ($config) {$MC = new Mem
   Cache
   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 a existing session should is overridden * * $lifetime = = False resets lifetime to Session.gc_maxlifetime * * @param int $lifetime * @param BooLean $overrideLifetime (Optional) * @return zend_session_savehandler_memcached/Public function setlifetime ($lif etime, $overrideLifetime = null) {if ($lifetime < 0) {/** * @see Zend_session_savehandler_exceptio
      n * * * * 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-&G
  T;_lifetime; }/** * Set whether or not the lifetime of a existing session should is overridden * * @param boolean $overrid Elifetime * @return zend_session_savehandler_memcached/Public function SEtoverridelifetime ($overrideLifetime) {$this->_overridelifetime = (Boolean) $overrideLifetime;
  return $this;
  The 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 funct
  Ion Close () {true;
    The public function read ($id) {$return = '; $value = $this->_memcached->get ($id);
      Gets the data if ($value) {if ($this->_getexpirationtime ($value) > Time ()) {$return = $value [' Data '];
      else {$this->destroy ($id);
  } return $return;
    The Public function write ($id, $data) {$return = false; $insertDate = Array (' Modified ' => time (), ' Data ' => (string) $data); $value = $this->_memcached->get ($id);
      Gets the data 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;
    The Public function destroy ($id) {$return = false;
    if ($this->_memcached->delete ($id)) {$return = true;
  return $return;
  The 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);

 }
}

Configuration (can add multiple memcache servers, do distributed):

$config = Array ('
  memcached ' => 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 ();

After the configuration, the session of the use of the same as before, without the bottom of the tube is how to achieve!

More interested in Zend related content readers can view the site topics: "The introduction of the Zend Framework frame", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Course", "PHP object-oriented Programming Program , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design based on the Zend Framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.