Skip to content
yuki-kimoto edited this page Oct 22, 2011 · 3 revisions

The way to Extend DBIx::Custom

package MyDBI;
use DBIx::Custom -base;

sub connect {
    my $self = shift->SUPER::new(@_);
    
    # Set dbi_option
    $self->dbi_option->{mysql_enable_utf8} = 1;

    # Connect
    $self->SUPER::connect;

    # Do something

    return $self;
}

Your class for MySQL

package DBIx::Custom::MySQL;
use DBIx::Custom -base;

has [qw/database host port/];

sub connect {
    my $proto = shift;
    
    # Create a new object
    my $self = ref $proto ? $proto : $proto->new(@_);
    
    # Data source
    if (!$self->data_source) {
        my $database = $self->database;
        my $host     = $self->host;
        my $port     = $self->port;
        my $data_source = "dbi:mysql:";
        $data_source .= "database=$database;" if $database;
        $data_source .= "host=$host;"         if $host;
        $data_source .= "port=$port;"         if $port;
        $self->data_source($data_source);
    }
    
    return $self->SUPER::connect;
}

1;

Your class for SQLite

package DBIx::Custom::SQLite;
use DBIx::Custom -base;

has 'database';

sub connect {
    my $proto = shift;
    
    # Create a new object
    my $self = ref $proto ? $proto : $proto->new(@_);
    
    # Data source
    my $database = $self->database;
    if (!$self->data_source && $database) {
        $self->data_source("dbi:SQLite:dbname=$database")
    }
    
    return $self->SUPER::connect;
}

sub connect_memory {
    my $self = shift->new(@_);
    
    # Data source
    $self->data_source('dbi:SQLite:dbname=:memory:');
    
    # Connect to database
    $self->connect;
    
    return $self;
}

1;
Clone this wiki locally