찾다
백엔드 개발PHP 튜토리얼Zend Framework가 Memcache에서 세션 저장소를 구현하는 방법에 대해

이 글에서는 주로 Zend Framework에서 Memcache에 세션을 저장하는 방법을 소개하고, Zend Framework에서 Memcache에 세션을 저장하는 구현 기법을 예시 형태로 분석합니다. Zend Framework는 Memcache에 세션을 저장하는 방법을 구현합니다. 참고하실 수 있도록 모두와 공유해 주세요. 자세한 내용은 다음과 같습니다.

zend 프레임워크에서는 이미 데이터베이스에 세션을 저장할 수 있지만 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 &#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 중국어 홈페이지를 주목해주세요!

관련 권장 사항:

Zend Framework의 Zend_Registry 구성 요소 사용 분석에 대해


Zend Framework에서 Json 데이터를 처리하는 방법에 대해


Zend Framework에서 Loader 및 PluginLoader의 사용 분석에 대해


위 내용은 Zend Framework가 Memcache에서 세션 저장소를 구현하는 방법에 대해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP의 전체 형태는 무엇입니까?PHP의 전체 형태는 무엇입니까?Apr 28, 2025 pm 04:58 PM

이 기사는 PHP에 대해 설명하고, 전체 형식, 웹 개발의 주요 용도, 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을 비교하여 대규모 웹 응용 프로그램, 성능 차이 및 보안 기능에 대한 적합성에 중점을 둡니다. 둘 다 대규모 프로젝트에서는 실용적이지만 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 Data Objects (PDO)에 대해 설명합니다. PHP의 데이터베이스 액세스 확장. 데이터베이스 추상화 및 더 나은 오류 처리를 포함하여 준비된 진술과 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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기