백엔드 개발 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支持,因为字符长度限制,我把部分注释去掉了):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

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服务器,做分布式):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

$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 기반 앱

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

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

Microsoft NET Framework 설치 문제 오류 코드 0x800c0006 수정 Microsoft NET Framework 설치 문제 오류 코드 0x800c0006 수정 May 05, 2023 pm 04:01 PM

.NET Framework 4는 개발자와 최종 사용자가 Windows에서 최신 버전의 애플리케이션을 실행하는 데 필요합니다. 그러나 .NET Framework 4를 다운로드하고 설치하는 동안 많은 사용자가 설치 프로그램이 중간에 중지되고 "오류 코드 0x800c0006으로 인해 다운로드에 실패했기 때문에 .NET Framework 4가 설치되지 않았습니다"라는 오류 메시지가 표시된다고 불평했습니다. 장치에 .NETFramework4를 설치하는 동안에도 이 문제가 발생한다면 올바른 위치에 있는 것입니다.

Windows 11/10에서 SetupDiag를 사용하여 Windows 업그레이드 문제를 식별하는 방법 Windows 11/10에서 SetupDiag를 사용하여 Windows 업그레이드 문제를 식별하는 방법 Apr 17, 2023 am 10:07 AM

Windows 11 또는 Windows 10 PC에 업그레이드 또는 업데이트 문제가 있을 때마다 일반적으로 실패의 실제 원인을 나타내는 오류 코드가 표시됩니다. 그러나 오류 코드가 표시되지 않고 업그레이드나 업데이트가 실패하면 혼란이 발생할 수 있습니다. 편리한 오류 코드를 사용하면 문제가 어디에 있는지 정확히 알 수 있으므로 문제를 해결할 수 있습니다. 하지만 오류 코드가 나타나지 않기 때문에 문제를 식별하고 해결하기가 어렵습니다. 단순히 오류의 원인을 찾는 데 많은 시간이 걸립니다. 이 경우 오류의 실제 원인을 쉽게 식별하는 데 도움이 되는 Microsoft에서 제공하는 SetupDiag라는 전용 도구를 사용해 볼 수 있습니다.

SpringBoot 세션에서 세션 시간 초과를 설정하는 방법 SpringBoot 세션에서 세션 시간 초과를 설정하는 방법 May 15, 2023 pm 02:37 PM

springboot 프로젝트 프로덕션 세션아웃 시간 초과에서 문제가 발견되었습니다. 문제 설명: 테스트 환경에서는 세션아웃 구성이 적용되었는지 확인하기 위해 application.yaml을 변경하여 세션아웃을 구성했습니다. , 프로덕션 환경에 도착하면 만료 시간이 8시간으로 직접 설정되었습니다. 그런데 정오에 고객으로부터 프로젝트 만료 시간이 짧게 설정되어 있다는 피드백을 받았습니다. 30분 동안 아무 작업도 수행하지 않으면 세션이 만료되어 반복 로그인이 필요합니다. 개발 환경 처리 문제를 해결합니다. springboot 프로젝트에는 Tomcat이 내장되어 있으므로 프로젝트의 application.yaml에 구성된 세션 아웃이 효과적입니다. 프로덕션 환경: 프로덕션 환경 릴리스는 다음과 같습니다.

세션 실패를 해결하는 방법 세션 실패를 해결하는 방법 Oct 18, 2023 pm 05:19 PM

세션 실패는 일반적으로 세션 수명 만료 또는 서버 종료로 인해 발생합니다. 해결 방법은 다음과 같습니다. 1. 세션 수명을 연장합니다. 3. 쿠키를 사용합니다. 4. 세션 관리 미들웨어를 사용합니다.

새로 고침 후 PHP 세션이 사라지면 어떻게 해야 합니까? 새로 고침 후 PHP 세션이 사라지면 어떻게 해야 합니까? Jan 18, 2023 pm 01:39 PM

새로 고침 후 PHP 세션이 사라지는 문제에 대한 해결 방법: 1. "session_start();"를 통해 세션을 엽니다. 2. 모든 공개 구성을 PHP 파일에 작성합니다. 3. 변수 이름은 배열 첨자와 같을 수 없습니다. 4. phpinfo에서 세션 데이터의 저장 경로를 확인하고 파일 디렉터리의 sessio가 성공적으로 저장되었는지 확인합니다.

PHP 세션 교차 도메인 문제에 대한 솔루션 PHP 세션 교차 도메인 문제에 대한 솔루션 Oct 12, 2023 pm 03:00 PM

PHPSession의 도메인 간 문제 해결 프런트엔드와 백엔드 분리 개발에서 도메인 간 요청이 표준이 되었습니다. 도메인 간 문제를 처리할 때 일반적으로 세션 사용 및 관리가 포함됩니다. 그러나 브라우저 원본 정책 제한으로 인해 기본적으로 도메인 간에 세션을 공유할 수 없습니다. 이 문제를 해결하려면 도메인 간 세션 공유를 달성하기 위한 몇 가지 기술과 방법을 사용해야 합니다. 1. 도메인 간 세션을 공유하기 위한 쿠키의 가장 일반적인 사용

SCNotification이 작동을 멈췄습니다. [수정을 위한 5단계] SCNotification이 작동을 멈췄습니다. [수정을 위한 5단계] May 17, 2023 pm 09:35 PM

Windows 사용자는 컴퓨터를 시작할 때마다 SCNotification이 작동을 중지했습니다. 오류가 발생할 수 있습니다. SCNotification.exe는 권한 오류 및 네트워크 오류로 인해 PC를 시작할 때마다 충돌이 발생하는 Microsoft 시스템 알림 파일입니다. 이 오류는 문제가 있는 이벤트 이름으로도 알려져 있습니다. 따라서 이를 SCNotification의 작동이 중지된 것으로 표시되지 않고 버그 clr20r3으로 표시될 수 있습니다. 이 기사에서는 SCNotification이 작동을 중지하여 다시 귀찮게 하지 않도록 수정하기 위해 취해야 할 모든 단계를 살펴보겠습니다. SCNotification.e는 무엇입니까

세션 PHP의 기본 만료 시간은 얼마입니까? 세션 PHP의 기본 만료 시간은 얼마입니까? Nov 01, 2022 am 09:14 AM

세션 PHP의 기본 만료 시간은 1440초(24분)입니다. 즉, 클라이언트가 24분 이상 새로 고치지 않으면 사용자가 브라우저를 닫으면 현재 세션이 만료되고 세션이 종료됩니다. 세션이 더 이상 존재하지 않습니다.

See all articles