ホームページ  >  記事  >  バックエンド開発  >  Zend Framework が memcache にセッション ストレージを実装する方法について

Zend Framework が memcache にセッション ストレージを実装する方法について

不言
不言オリジナル
2018-06-15 14:43:361198ブラウズ

この記事では、Zend Framework でセッションを memcache に保存する方法を主に紹介し、Zend Framework フレームワークでセッションを memcache に保存する実装テクニックを例に基づいて分析します。

この記事の例では、Zend Framework がセッションを memcache に保存する方法について説明します。参考までに皆さんと共有してください。詳細は次のとおりです。

zend フレームワークではすでにセッションをデータベースに保存できますが、memcache はまだサポートされていないため、単純に実装しました。

次は SaveHandler です。ファイル名は Memcached.php です。コードは次のとおりです (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 &#39;Zend/Session/SaveHandler/Exception.php&#39;;
      throw new Zend_Session_SaveHandler_Exception();
    } else if (empty($lifetime)) {
      $this->_lifetime = (int) ini_get(&#39;session.gc_maxlifetime&#39;);
    } 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 = &#39;&#39;;
    $value = $this->_memcached->get($id); //获取数据
    if ($value) {
      if ($this->_getExpirationTime($value) > time()) {
        $return = $value[&#39;data&#39;];
      } else {
        $this->destroy($id);
      }
    }
    return $return;
  }
  public function write($id, $data)
  {
    $return = false;
    $insertDate = array(&#39;modified&#39; => time(),
               &#39;data&#39;   => (string) $data);
      $value = $this->_memcached->get($id); //获取数据
    if ($value) {
      $insertDate[&#39;lifetime&#39;] = $this->_getLifetime($value);
      if ($this->_memcached->replace($id,$insertDate)) {
        $return = true;
      }
    } else {
      $insertDate[&#39;lifetime&#39;] = $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[&#39;lifetime&#39;];
    }
    return $return;
  }
  protected function _getExpirationTime($value)
  {
    return (int) $value[&#39;modified&#39;] + $this->_getLifetime($value);
  }
}

構成 (配布用に複数の memcache サーバーを追加できます):

$config = array(
  &#39;memcached&#39;=> array(
    array(
      &#39;ip&#39;=>&#39;192.168.0.1&#39;,
      &#39;port&#39;=>11211
    )
  ),
  &#39;lifetime&#39; =>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();

構成後は、基礎となる層がどのように実装されているかに関係なく、セッションは以前と同様に使用されます。

上記がこの記事の全内容です。その他の関連コンテンツについては、PHP 中国語 Web サイトをご覧ください。

関連する推奨事項:

Zend Framework の Zend_Registry コンポーネントの使用分析について

Zend Framework の Json データ処理方法について

Zend Framework における Loader および PluginLoader の使用状況分析について

#

以上がZend Framework が memcache にセッション ストレージを実装する方法についての詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。