end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

Amon2のO/RマッパーをTeng→DBIx::Classに変更

※一連のAmon2関連の写経は、これで、一旦、終了

Amon2のデフォルトのorマッパーはTengですが、試しに DBIx::Class (dbic)に変更。
http://amon.64p.org/database.html

STEP1 - dbicスキーマクラスを作成

DBIx::Class::Schema::LoaderによるDBIC用スキーマ自動作成 - end0tknrのkipple - web写経開発
↑こちらを参考に↓このように自動作成。

lib/TestAmon2App/Schema.pm
lib/TestAmon2App/Result/FollowingMap.pm
lib/TestAmon2App/Result/Tweet.pm
lib/TestAmon2App/Result/User.pm
lib/TestAmon2App/Result/UserProfile.pm

※自動生成されたクラス群ですので、各srcの内容は記載しません
※スケルトン作成時に自動生成されていたTeng用のクラスは、使いません
(面倒なので削除もしませんでした)

lib/TestAmon2App/DB.pm
lib/TestAmon2App/DB/Row.pm
lib/TestAmon2App/DB/Schema.pm

STEP2 - appルートクラスにある db()メソッドを変更

package TestAmon2App;
use TestAmon2App::DB::Schema;
use TestAmon2App::DB;

sub db {
    my $c = shift;
    if (!exists $c->{db}) {
        my $conf = $c->config->{DBI}
            or die "Missing configuration about DBI";
        $c->{db} = TestAmon2App::DB->new(
            schema       => $schema,
            connect_info => [@$conf],
            # I suggest to enable following lines if you are using mysql.
            # on_connect_do => [
            #     'SET SESSION sql_mode=STRICT_TRANS_TABLES;',
            # ],
        );
    }
    $c->{db};

Teng用の↑こちらを、dbic用に↓このように変更

package TestAmon2App;
use TestAmon2App::Schema;

sub db {
    my $c = shift;
    if (!exists $c->{db}) {
        my $conf = $c->config->{DBI} or die "Missing configuration about DBI";
        $c->{db} = TestAmon2App::Schema->connect(@{$c->config->{DBI}})
    }
    return $c->{db};
}
}

STEP3 - 試しにコントローラクラスで使います

↓この通リ

package TestAmon2App::Web::Dispatcher;
# :
any '/' => sub {
    my ($c) = @_;

    ####↓ココ
    my $schema = $c->db;
    my @users = $schema->resultset('User')->all;
    for my $user ( @users ){
        print STDERR join(' ',"USERNAME=",$user->username ),"\n";
    }

    my $counter = $c->session->get('counter') || 0;
    $counter++;
    $c->session->set('counter' => $counter);
    return $c->render('index.tx', {
        counter => $counter,
    });

};

その他

いずれも、本エントリの本題とは関係ありませんが...

DBICトランザクション処理

ググると、txn_do()というmethodが見つかりますが、DBICトランザクション処理したことありません。

DBIx::Class::ResultSetManager は、DEPRECATE

amon2(PSGI)サーバの起動時に次のように表示され、初めて気付きました。

$ perl ./script/testamon2app-server -host colinux.a4.jp
DBIx::Class::ResultSetManager never left experimental status and
has now been DEPRECATED. This module will be deleted in 09000 so please
migrate any and all code using it to explicit resultset classes using either
__PACKAGE__->resultset_class(...) calls or by switching from using
DBIx::Class::Schema->load_classes() to load_namespaces() and creating
appropriate My::Schema::ResultSet::* classes for it to pick up. at /usr/local/lib/perl5/site_perl/5.18.2/DBIx/Class/ResultSetManager.pm line 8.
DBIx::Class::Componentised::inject_base(): Use of DBIx::Class::UTF8Columns is strongly discouraged. See documentation of DBIx::Class::UTF8Columns for more info
TestAmon2App: http://colinux.a4.jp:5000/