首頁 後端開發 php教程 Zend Framework实现将session存储在memcache中的方法_PHP

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

May 27, 2016 am 10:34 AM
framework session zend

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

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Microsoft NET Framework 安裝問題 錯誤代碼 0x800c0006 修復 Microsoft NET Framework 安裝問題 錯誤代碼 0x800c0006 修復 May 05, 2023 pm 04:01 PM

.NETFramework4是開發人員和最終使用者在Windows上執行最新版本的應用程式所必需的。但是,在下載安裝.NETFramework4時,許多用戶抱怨安裝程式在中途停止,顯示以下錯誤訊息-「 .NETFramework4hasnotbeeninstalledbecauseDownloadfailedwitherrorcode0x800c0006 」。在您的裝置上安裝.NETFramework4時,如果您也在體驗它,那麼您就來對了地方

如何在 Windows 11/10 上使用 SetupDiag 識別 Windows 升級問題 如何在 Windows 11/10 上使用 SetupDiag 識別 Windows 升級問題 Apr 17, 2023 am 10:07 AM

每當您的Windows11或Windows10PC出現升級或更新問題時,您通常會看到一個錯誤代碼,指示故障背後的實際原因。但是,有時,升級或更新失敗可能不會顯示錯誤代碼,這時就會混淆。有了方便的錯誤代碼,您可以確切地知道問題出在哪裡,因此您可以嘗試修復。但是由於沒有出現錯誤代碼,因此識別問題並解決它變得極具挑戰性。這會佔用您大量時間來簡單地找出錯誤背後的原因。在這種情況下,您可以嘗試使用Microsoft提供的名為SetupDiag的專用工具,該工具可協助您輕鬆識別錯誤背後的真

SpringBoot Session怎麼設定會話超時 SpringBoot Session怎麼設定會話超時 May 15, 2023 pm 02:37 PM

問題發現springboot專案生產session-out逾時問題,描述下問題:在測試環境透過改動application.yaml配置session-out,經過設定不同時間驗證session-out配置生效,於是就直接設定了過期時間為8小時發布到了生產環境。然而中午接到客戶反應項目過期時間設定較短,半小時不操作就會話過期需要重複登陸。解決處理開發環境:springboot專案內建Tomcat,所以專案中application.yaml配置session-out是生效的。生產環境:生產環境發布是

session失效怎麼解決 session失效怎麼解決 Oct 18, 2023 pm 05:19 PM

session失效通常是由於 session 的生存時間過期或伺服器關閉導致的。其解決方法:1、延長session的生存時間;2、使用持久化儲存;3、使用cookie;4、非同步更新session;5、使用會話管理中介軟體。

SCNotification 已停止運作 [修復它的 5 個步驟] SCNotification 已停止運作 [修復它的 5 個步驟] May 17, 2023 pm 09:35 PM

身為Windows用戶,您很可能會在每次啟動電腦時遇到SCNotification已停止工作錯誤。 SCNotification.exe是一個微軟系統通知文件,由於權限錯誤和點網故障等原因,每次啟動PC時都會崩潰。此錯誤也以其問題事件名稱而聞名。因此,您可能不會將其視為SCNotification已停止工作,而是將其視為錯誤clr20r3。在本文中,我們將探討您需要採取的所有步驟來修復SCNotification已停止運作,以免它再次困擾您。什麼是SCNotification.e

PHP Session 跨域問題的解決方法 PHP Session 跨域問題的解決方法 Oct 12, 2023 pm 03:00 PM

PHPSession跨域問題的解決方法在前後端分離的開發中,跨域請求已成為常態。在處理跨域問題時,我們通常會涉及session的使用和管理。然而,由於瀏覽器的同源策略限制,跨域情況下預設無法共享session。為了解決這個問題,我們需要採用一些技巧和方法來實現session的跨域共享。一、使用cookie跨域共享session最常

php session刷新後沒有了怎麼辦 php session刷新後沒有了怎麼辦 Jan 18, 2023 pm 01:39 PM

php session刷新後沒有了的解決方法:1、透過「session_start();」開啟session;2、把所有的公共配置寫在一個php檔案內;3、變數名稱不能和陣列下標相同;4、在phpinfo裡面查看session資料的儲存路徑,並查看該檔案目錄下的sessio是否儲存成功即可。

session php預設失效時間是多少 session php預設失效時間是多少 Nov 01, 2022 am 09:14 AM

session php預設失效時間是1440秒,也就是24分鐘,表示客戶端超過24分鐘沒有刷新,當前session就會失效;如果使用者關閉了瀏覽器,會話就會結束,Session就不存在了。

See all articles