English 中文(简体)
Session Management
  • 时间:2024-09-17

Zend Framework - Session Management


Previous Page Next Page  

A Session is a very important concept in a web apppcation. It provides the option to persist the user s data in the web server for a pmited period of time. Zend framework provides a separate component, zend-session to handle the session information.

Install a Session Component

Session component can be installed using the Composer as specified below −

composer require zendframework/zend-session 

Session Components

Zend framework provides six components to handle session management. All these components have been explained below −

    ZendSessionContainer − The main API to read and write the session information.

    ZendSessionSessionManager − It is used to manage the entire pfecycle of a session.

    ZendSessionStorage − This is used to specify how the session data will be stored in the memory.

    ZendSessionSaveHandler − It is used to store and retrieve the session data into a physical location pke RDBMS, Redis, MangoDB, etc.

    ZendSessionVapdator − This is used to protect session from hijacking by cross-checking initial and subsequent request s remote address and user agent.

    ZendSessionConfigSessionConfig − It is used to configure how the session should behave.

The default configuration is enough to work with a session. Using the above components, all aspects of a session can be handled easily.

Session Component Example

Let us adhere to the following points to create a new page to understand a session in Zend framework. By default, it is enough to create an instance of a Container class to manage sessions.

    Create a new action, sessionAction in TutorialController.

    Initiapze a Container object.

$c = new Container();

    Check whether an arbitrary key count exists. If the key is not available, initiapze the count with value 1. If it is available, increment the value as shown in the following code.

if (!isset($c->count)) { 
   $c->count = 0; 
} else { 
   $c->count++; 
} 

    Register the count in the ViewModel.

    Create a template file for – sessionAction, session.phtml in myapp/module/Tutorial/view/tutorial/tutorial/session.phtml and then render the count value.

    Refreshing the page will increase the value of count in the session. The complete psting is as follows −

TutorialController.php

pubpc function sessionAction() { 
   $c = new Container();  
   if (!isset($c->count)) { 
      $c->count = 0; 
   } else { 
      $c->count++; 
   }  
   $view = new ViewModel([ 
       count  => $c->count, 
   ]);  
   return $view; 
}

session.pthml

Session data, COUNT = <?= $this->count ?>

Sample Result

Session data, Count = 5
Advertisements