Kilátó
Kilátó

Reputation: 413

How to initialize a session in Catalyst application?

here is the myapp's module from the lib folder:

package myapp;
use Moose;
use namespace::autoclean;
use Catalyst::Runtime 5.80;
use Catalyst qw/
    ConfigLoader
    Session
    Session::Store
    Session::State
    Static::Simple
/;

extends 'Catalyst';
our $VERSION = '0.01';

__PACKAGE__->config(
    name => 'myapp',
    # Disable deprecated behavior needed by old applications
    disable_component_resolution_regex_fallback => 1,
    enable_catalyst_header => 1, # Send X-Catalyst header
);

sub init {
    my ( $c ) = @_;
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
    $c->session->{ed_year} = $year + 1900;
}

# Start the application
__PACKAGE__->setup();
__PACKAGE__->init();

1;

The example above is wrong, there is no available context($c). I would like to know if it is possible to initialize a session in a Catalyst application right in its main module. Here I would like to initialize global variables, used later by views, models and controllers?

Best regards, SK

Upvotes: 0

Views: 236

Answers (1)

RET
RET

Reputation: 9188

A session is associated with a user, and is an artifact of interaction with that user. You can't create a session in the main program - as you rightly say, there's no context at that point. In any case, what I think you're wanting to do is to configure some variables that will be available to any user of the application, so they're global, not user-specific anyway.

Use __PACKAGE__->config - it's just a hashref, and that's what it's for. You're certainly not limited to the documented keys.

For example:

__PACKAGE__->config(
    name => 'myapp',
    # Disable deprecated behavior needed by old applications
    disable_component_resolution_regex_fallback => 1,
    enable_catalyst_header => 1, # Send X-Catalyst header
    ed_year => (localtime())[5] + 1900,
    foo => { bar => 1, baz => 'quux' },
);

In your models, views and controllers those values will be available as $c->config->{ed_year} and $c->config->{foo}->{baz} and so on.

By the way, perhaps your use of ed_year was just a simplistic example, but consider how that will be instantiated: it will be the date and time the server is started, not the time of the current request. If the latter is what you want, put it in the auto handler of your Root.pm controller. And don't roll your own with localtime, use the DateTime module.

Upvotes: 2

Related Questions