• 追加された行はこの色です。
  • 削除された行はこの色です。
* ルーティング [#k72c01bb]

** デフォルトルーティング [#u743da58]


 sub startup {
   $r->route('/:x/:y')->to('test#index', id => 1);
    my $r = $self->routes;
    $r->route('/:x/:y')->to('test#index', id => 1);
 }

 package MyApp:Test;
 sub index {
   $self->stash->{x};  # foo
   $self->stash->{y};  # bar
   $self->stash->{id}; # 1
    $self->stash->{x};  # foo
    $self->stash->{y};  # bar
    $self->stash->{id}; # 1
 }

- 以上の場合、route()で2つのパスを持つ引数を指定しているので、http://localhost:3000/foo/barのようなURLを受け付ける。
-- もし、http://localhost:3000/foo/bar/bazのようなURLを受け付けるには、route('/:a/:b/:c')と指定する必要がある。
- そして、コントローラにより、MyApp::Testクラスのindexメソッドが実行される。
- メソッド内ではstashの中にURLで指定したパスが入っている。
- 以上の場合、route()で2つのパスを持つ引数を指定している(xやyは後述のようにメソッド内での変数名になる)ので、http://localhost:3000/foo/barのようなURLを受け付ける。
-- もし、http://localhost:3000/foo/bar/bazのようなURLを受け付けるには、route('/:a/:b/:c')のように指定する必要がある。
- ルーティング設定を元にMyApp::Testクラスのindexメソッドが実行される。
- メソッド内ではstashの中にxやyをキー名にしてURLで指定したパスが値として入っている。

** bridge()を使って共通初期処理とアクセス制御 [#h4a87093]
 sub startup {
    my $self = shift;
    my $r = $self->routes;
    my $init = $r->bridge->to(controller => 'util', action => 'init');
 
    $init->route("/index")->to(controller => 'top', action => 'index')->name('top');
    $init->route("/login/index")->to(controller => 'login', action => 'index')->name('login/index');
    $init->route("/login/logout")->to(controller => 'login', action => 'logout')->name('login/logout');
 
    my $auth_ok = $init->bridge->to(controller => 'common', action => 'auth');
    $auth_ok->route("/blog/list")->to(controller => 'blog', action => 'list')->name('blog/list');
    $auth_ok->route("/blog/edit")->to(controller => 'blog', action => 'edit')->name('blog/edit');
 }

 package MyApp:Util;
 # 共通初期処理
 sub init {
    $self->stash->{session}->load;
    $self->stash->{session}->create unless $self->stash->{session}->sid;
    $self->{stash}->{auth} = undef;
    if ( $self->stash->{session}->data('auth') ) {
        $self->{stash}->{auth} = $self->stash->{session}->data('auth');
    }
    return 1;
 }
 # ログイン判定
 sub auth {
    my $self = shift;
    unless ( $self->stash->{auth} ) {
        $self->stash->{session}->data( 'status_mesg' => 'ログインして下さい。' );
        $self->redirect_to('login/index');
        return;
    }
    return 1;
 }
- 最初に共通初期処理(Util::init)を行う。
- /indexと/login/indexと/login/logoutのURLに関してはそのままコントローラクラス内のメソッドを実行する。
- それ以外のURLについてはログイン判定(Util::auth)を行い、パスすればコントローラクラス内のメソッドを実行するし、パスしなければログイン画面(/login/index)にリダイレクトする。


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS