mod_perlハンドラでセッションを使う

mod_perlのアプリケーションで、いわゆる「セッション」を使いたいときは Apache::Session::Wrapper モジュールを使うことができる。
以下のプログラムでは1セッション1ファイルに保存するように設定しているが、保存先はPostgreSQLMySQL、dbmなどを選ぶこともできる。

セッションに保存する

package My::SaveSession;
use strict;

use Apache2::RequestRec;
use Apache2::RequestIO;
use Apache2::Const -compile => 'OK';

use Apache::Session::Wrapper;

sub handler : method {
    my ($class, $r) = @_;

    $r->content_type('text/html');

    my $wrapper = Apache::Session::Wrapper->new(
                    class  => 'File',
                    directory => '/home/www/session',
                    lock_directory => '/home/www/session/lock',
                    use_cookie => 1,
                 );
    $wrapper->session->{test_param} = 'test string';

    print q|<a href="/show_session">show_session</a>|;

    return Apache2::Const::OK;
}

1;

セッションから取り出す(こちらのハンドラには /show_session というURLを割り当てている)

package My::ShowSession;
use strict;

use Apache2::RequestRec;
use Apache2::RequestIO;
use Apache2::Const -compile => 'OK';

use Apache::Session::Wrapper;

sub handler : method {
    my ($class, $r) = @_;

    $r->content_type('text/plain');

    my $wrapper = Apache::Session::Wrapper->new(
                    class  => 'File',
                    directory => '/home/www/session',
                    lock_directory => '/home/www/session/lock',
                    use_cookie => 1,
                 );
    print $wrapper->session->{test_param};

    return Apache2::Const::OK;
}

1;