DBの設定などはこちらに沿っています。
今回は、以下のコマンドでアプリケーションの雛形を作成した場合です。
$ amon2-setup.pl Hello
config/development.plの編集
Teng用の設定を書いておきます。
+{ 'Teng' => { dsn => 'dbi:SQLite:dbname=hello.db', username => '', password => '', }, ... };
スキーマ作成スクリプト
DBの情報を読み込んでスキーマを作成するスクリプトを書きます。
use strict; use warnings; use DBI; use FindBin; use File::Spec; use lib File::Spec->catdir($FindBin::Bin, '..', 'lib'); use lib File::Spec->catdir($FindBin::Bin, '..', 'extlib', 'lib', 'perl5'); use Hello; use Teng::Schema::Dumper; my $c = Hello->bootstrap; my $conf = $c->config->{'Teng'}; my $dbh = DBI->connect($conf->{dsn}, $conf->{username}, $conf->{password}, $conf->{connect_options}) or die "Cannot connect to DB:: " . $DBI::errstr; my $schema = Teng::Schema::Dumper->dump(dbh => $dbh, namespace => 'Hello::DB'); my $dest = File::Spec->catfile($FindBin::Bin, '..', 'lib', 'Hello', 'DB', 'Schema.pm'); open my $fh, '>', $dest or die "cannot open file '$dest': $!"; print {$fh} $schema; close;
「script/make_schema.pl」で保存して、実行します。
実行すると「lib/Hello/DB/Schema.pm」が作成されます。
lib/Hello/DB.pmの作成
lib/Hello/DB.pmを作成して、以下の内容を記述します。
package Hello::DB; use parent 'Teng'; 1;
lib/Hello.pmの編集
コントローラの方でTengが使えるようにHello.pmに以下の内容を追記します。
... use Hello::DB; sub db { my ($self) = @_; if (!defined $self->{db}) { my $conf = $self->config->{'Teng'} or die "missing configuration for 'Teng'"; my $dbh = DBI->connect($conf->{dsn}, $conf->{username}, $conf->{password}, $conf->{connect_options}) or "Cannot connect to DB:: " . $DBI::errstr; $self->{db} = Hello::DB->new({ dbh => $dbh }); } return $self->{db}; } ...
これで、コントローラの方では以下のようにして使うことができます。
sub index { my ($class, $c) = @_; my @entries = $c->db->search( entry => {}, { limit => 10, offset => 0, order_by => {'entry_id' => 'DESC' }}); $c->render( "index.tt" => { entries => \@entries, } ); }
参考リンク
これで使えるようになったので、以下のリンクを参照しながら使い方を覚えていきたいと思います。