日記はScrapboxに移動しました。

CuteというWebフレームワークを作った

俺々フレームワークを作ってみたかったので、先人の知恵をいろいろ拝借する感じでやってみた。

いろいろ足りないものがあるけど、まあとりあえず動くところまで。自分の好み的に、わりといい感じになりつつあるので、今後は、個人用プロジェクトにはこれを使っていきたい。

いちファイルでこんなん書いたら適当に動く感じ。

package Example::Cute::Default;
use strict;
use warnings;
use Cute;
sub title {
my ($self, $suffix) = @_;
my $title  = 'Hello, Cute!';
$title .= " ($suffix)" if $suffix;
$title;
}
get '/' => sub {
my ($self, $ctx) = @_;
};
get '/foo' => sub {
my ($self, $ctx) = @_;
$ctx->res->content($self->title('/foo'));
};
get '/bar/baz' => sub {
my ($self, $ctx) = @_;
$ctx->stash(
title => $self->title('/bar/baz'),
list  => [
{ value => 'foo' },
{ value => 'bar' },
{ value => 'baz' },
],
);
};
get '/{year:[0-9]{4}}/{month:[0-9]{2}}' => sub {
my ($self, $ctx) = @_;
$ctx->response->set_template('path_query.html');
$ctx->stash(
year  => $ctx->req->path_query('year'),
month => $ctx->req->path_query('month'),
);
};
!!1;

んでもって、それだと規模が大きくなると見通しが悪くなりそうなので、Controller別にも分けられるようにもしてみた。::Contoler::Hogeみたいなのの中では、get/post/put/deleteが、自動的に/hoge以下を指すようになる。

package Example::Cute::Default::Controller::Hoge;
use strict;
use warnings;
use Cute 'Example::Cute::Default';
get '/' => sub {
my ($self, $ctx) = @_;
$ctx->res->content($self->title('/hoge'));
};
get '/fuga' => sub {
my ($self, $ctx) = @_;
$ctx->stash(
title => $self->title('/hoge/fuga'),
list  => [
{ value => 'foo' },
{ value => 'bar' },
{ value => 'baz' },
],
);
};
!!1;

上の例は以下から見ることができる。

Leave a Reply

Your email address will not be published. Required fields are marked *