2008년 6월 9일 월요일

앞으로 DBI대신에 DBix::class를 사용하기로 함.

DBIx::Class - Extensible and flexible object <-> relational mapper.
확장이 가능하다라, 어떻게 확장을 하겠다는 이야기인지?

샘플:
step 1. 먼저 사용자 객체를 생성한다.
1. Create a schema class called DB/Main.pm:

package DB::Main;
  use base qw/DBIx::Class::Schema/;

  __PACKAGE__->load_classes();

  1;

2. Create a table class to represent artists, who have many CDs, in DB/Main/Artist.pm:

package DB::Main::Artist;
  use base qw/DBIx::Class/;

  __PACKAGE__->load_components(qw/PK::Auto Core/);
  __PACKAGE__->table('artist');
  __PACKAGE__->add_columns(qw/ artistid name /);
  __PACKAGE__->set_primary_key('artistid');
  __PACKAGE__->has_many(cds => 'DB::Main::CD');

  1;

3. DB/Main/CD.pm 에 CD class 생성

package DB::Main::CD;
  use base qw/DBIx::Class/;

  __PACKAGE__->load_components(qw/PK::Auto Core/);
  __PACKAGE__->table('cd');
  __PACKAGE__->add_columns(qw/ cdid artist title year /);
  __PACKAGE__->set_primary_key('cdid');
  __PACKAGE__->belongs_to(artist => 'DB::Main::Artist');

  1;



step 2. 프로그램 내부에서 사용
###################################################
# Connect to your database.
  use DB::Main;
  my $schema = DB::Main->connect($dbi_dsn, $user, $pass, \%dbi_params);
# dbi_params는 어떤것이지?

# Query for all artists and put them in an array,
  # or retrieve them as a result set object.
  my @all_artists = $schema->resultset('Artist')->all;
  my $all_artists_rs = $schema->resultset('Artist');

# where 조건을 만들어 넣는군..흠흠..
# Create a result set to search for artists.
  # This does not query the DB.
  my $johns_rs = $schema->resultset('Artist')->search(
    # Build your WHERE using an SQL::Abstract structure:
    { name => { like => 'John%' } }
  );

# Fetch only the next row.
  my $first_john = $johns_rs->next;

등등..흠 초기에 설정만 잘 해 놓으면 쉽게 사용이 가능하겠군.
굳이 좋은 점이라면 여러군데 산재되어 있는 query의 컨트롤 가능?




댓글 없음:

댓글 쓰기