検索
ホームページバックエンド開発PHPチュートリアルZend Framework が memcache にセッション ストレージを実装する方法について

この記事では、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 までご連絡ください。
PHPの完全な形式は何ですか?PHPの完全な形式は何ですか?Apr 28, 2025 pm 04:58 PM

この記事では、PHPについて説明し、その完全なフォーム、Web開発での主要な使用、PythonとJavaとの比較、および初心者の学習のしやすさについて説明します。

PHPはフォームデータをどのように処理しますか?PHPはフォームデータをどのように処理しますか?Apr 28, 2025 pm 04:57 PM

PHPは、$ \ _ postおよび$ \ _を使用してフォームデータを処理し、検証、消毒、安全なデータベースインタラクションを通じてセキュリティを確保します。

PHPとASP.NETの違いは何ですか?PHPとASP.NETの違いは何ですか?Apr 28, 2025 pm 04:56 PM

この記事では、PHPとASP.NETを比較して、大規模なWebアプリケーション、パフォーマンスの違い、セキュリティ機能への適合性に焦点を当てています。どちらも大規模なプロジェクトでは実行可能ですが、PHPはオープンソースであり、プラットフォームに依存しませんが、ASP.NET、

PHPはケースに敏感な言語ですか?PHPはケースに敏感な言語ですか?Apr 28, 2025 pm 04:55 PM

PHPの症例感度は変化します:関数は鈍感であり、変数とクラスは感度があります。ベストプラクティスには、一貫した命名と、比較のためにケース非感受性関数を使用することが含まれます。

PHPでページをリダイレクトするにはどうすればよいですか?PHPでページをリダイレクトするにはどうすればよいですか?Apr 28, 2025 pm 04:54 PM

この記事では、PHPのページリダイレクトのさまざまな方法について説明し、ヘッダー()関数に焦点を当て、「すでに送信されているヘッダー」エラーなどの一般的な問題に対処します。

PHPでヒントを示すタイプを説明しますPHPでヒントを示すタイプを説明しますApr 28, 2025 pm 04:52 PM

記事では、PHPでヒントを示すタイプについて説明します。これは、機能内の予想データ型を指定する機能です。主な問題は、タイプの施行を通じてコードの品質と読みやすさを改善することです。

PHPのPDOとは何ですか?PHPのPDOとは何ですか?Apr 28, 2025 pm 04:51 PM

この記事では、PHPのデータベースアクセスの拡張機能であるPHPデータオブジェクト(PDO)について説明します。これは、データベースの抽象化やより良いエラー処理など、準備されたステートメントとMySQLIに対する利点を通じてセキュリティを強化する上でのPDOの役割を強調しています。

PHPでAPIを作成する方法は?PHPでAPIを作成する方法は?Apr 28, 2025 pm 04:50 PM

記事では、PHP APIの作成とセキュリティについて説明し、LaravelなどのフレームワークやBest Security Practicesなどのフレームワークを使用して、エンドポイントの定義からパフォーマンスの最適化までの手順を詳細に説明します。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター