Catalyst Advent - Day 15 - Sessions

When you have your users identified, you will want to somehow remember that fact, to save them from having to identify themselves for every single page. One way to do this is to send the username and password parameters in every single page, but that's ugly, and won't work for static pages.

Sessions are a method of saving data related to some transaction, and giving the whole collection a single ID. This ID is then given to the user to return to us on every page they visit while logged in. The usual way to do this is using a browser cookie.

Catalyst uses two types of plugins to represent sessions:

State

A State module is used to keep track of the state of the session between the users browser, and your application.

A common example is the Cookie state module, which sends the browser a cookie containing the session ID. It will use default value for the cookie name and domain, so will "just work" when used.

Store

A Store module is used to hold all the data relating to your session, for example the users ID, or the items for their shopping cart. You can store data in memory (FastMmap), in a file (File) or in a database (DBI).

Authentication magic

If you have included the session modules in your application, the Authentication modules will automagically use your session to save and retrieve the user data for you.

Using a session

Once the session modules are loaded, the session is available as $c->session, and can be writen to and read from as a simple hash reference.

EXAMPLE

  use Catalyst qw/
                 Session
                 Session::Store::FastMmap
                 Session::State::Cookie
                 /;




  ## Write data into the session

  sub add_item : Local {
     my ( $self, $c ) = @_;

     my $item_id = $c->req->param("item");

     push @{ $c->session->{items} }, $item_id;

  }

  ## A page later we retrieve the data from the session:

  sub get_items : Local {
     my ( $self, $c ) = @_;

     $c->stash->{items_to_display} = $c->session->{items};

  }




More information