Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests. hunt-framework ships with a variety of session backends that are accessed through an expressive, unified API. Support for popular backends such as Redis, and memory is included out of the box. That's because the session storage depends on the Hunt-Cache.
The configuration for session is stored in config/application.conf
. Be sure to review the options available to you in this file. If the backend's settings will use the ones for Cache.
# Session
session.prefix = huntsession_
session.expire = 3600
# redis, memory
cache.adapter = redis
cache.prefix = huntcache_
cache.expire = 3600
{tip} More item value reference file ApplicationConfig.d
{tip} More reference file reference
There are two primary ways of working with session data in hunt-framework: the global session
helper and via a Request
instance. First, let's look at accessing the session via a Request
instance, which can be type-hinted on a controller method. Remember, controller method dependencies are automatically injected via the hunt-framework :
request.session.get("KEY");
If you would like to retrieve all the data in the session, you may use the all
method:
string[string] data = request.session.all();
To determine if an item is present in the session, you may use the exists
method:
if (request.session.exists("KEY");) {
//
}
To store data in the session, you will typically use the set
method :
// Via a request instance...
request.session.set("key", "value");
The push
method may be used to push a new value onto a session value that is an array. For example, if the teams
key contains an array of team names, you may push a new value onto the array like so:
request.session.push("teams", "developers");
The remove
method will remove a piece of data from the session:
// Forget a single key...
request.session.remove('key');