PHP Classes

File: manuscript/8b. Session usage.md

Recommend this page to a friend!
  Classes of Gjero Krsteski   PIMF   manuscript/8b. Session usage.md   Download  
File: manuscript/8b. Session usage.md
Role: Auxiliary data
Content type: text/markdown
Description: Auxiliary data
Class: PIMF
Framework for Web application development
Author: By
Last change: Update of manuscript/8b. Session usage.md
Date: 5 months ago
Size: 2,009 bytes
 

Contents

Class file image Download

Session usage

To store items in the session call the put method on the Session class.

Pimf\Session::put('name', 'Rob');

The first parameter is the key to the session item. You will use this key to retrieve the item from the session. The second parameter is the value of the item.

You can use the get method on the Session class to retrieve any item in the session, including flash data. Just pass the key of the item you wish to retrieve:

$name = Pimf\Session::get('name');

By default, NULL will be returned if the session item does not exist. However, you may pass a default value as a second parameter to the get method:

$name = Pimf\Session::get('name', 'Rob');
$name = Pimf\Session::get('name', function() {return 'Rob';});

PIMF even provides a simple way to determine if a session item exists using the has method:

if (Session::has('name')) {
     $name = Pimf\Session::get('name');
}

To remove an item from the session use the forget method on the Session class.

Pimf\Session::forget('name');

You can even remove all of the items from the session using the flush method.

Pimf\Session::flush();

The flash method stores an item in the session that will expire after the next request. It`s useful for storing temporary data like status or error messages:

Pimf\Session::flash('status', 'Welcome Back!');

Flash items that are expiring in subsequent requests can be retained for another request by using one of the reflash or keep methods:

Retain all items for another request:

Pimf\Session::reflash();

Retain an individual item for another request:

Pimf\Session::keep('status');

Retain several items for another request:

Pimf\Session::keep(array('status', 'other_item'));

Sometimes you may want to "regenerate" the session ID. This simply means that a new, random session ID will be assigned to the session. Here's how to do it:

Pimf\Session::regenerate();