It's not on CPAN yet (waiting for PAUSE id),
but you might want to check out
SPOPS: Simple Perl Object
Persistence with Security. Here's a simple
example using DBI (just swiping one of the
eg/ files from the distribution):
#!/usr/bin/perl
use strict;
use DBI;
use SPOPS::Configure::DBI;
use Data::Dumper qw( Dumper );
# Change these lines as needed (test is normally
# setup for MySQL tho...)
my $DBI_DSN = 'DBI:mysql:test';
my $DBI_USERNAME = '';
my $DBI_PASSWORD = '';
my $db = DBI->connect( $DBI_DSN, $DBI_USERNAME, $DBI_PASSWORD )
|| die "Cannot connect! Error: $DBI::errstr";
$db->{RaiseError} = 1;
my $fb_table = <<'SQL';
CREATE TABLE fatbomb (
fatbomb_id int not null auto_increment,
name varchar(100) null,
calories int null,
cost varchar(10) null,
servings smallint null default 15,
primary key ( fatbomb_id )
)
SQL
$db->do( $fb_table );
my $spops = {
fatbomb => {
class => 'My::ObjectClass',
isa => [ qw/ SPOPS::DBI::MySQL SPOPS::DBI / ],
field => [ qw/ fatbomb_id calories cost name servings /
+],
base_table => 'fatbomb',
id_field => 'fatbomb_id',
skip_undef => [ qw/ servings / ],
sql_defaults => [ qw/ servings / ],
},
};
SPOPS::Configure::DBI->process_config({
config => $spops,
require_isa => 1
});
My::ObjectClass->class_initialize;
my $object = My::ObjectClass->new;
$object->{calories} = 1500;
$object->{cost} = '$3.50';
$object->{name} = "Super Deluxe Jumbo Big Mac";
my $fb_id = eval { $object->save( { db => $db } ) };
if ( $@ ) {
my $ei = SPOPS::Error->get;
die "Error found! ($@) Error information:\n",
"System Message: $ei->{system_msg}\n",
"Extra Stuff: $ei->{extra}->{sql}\n",
"$ei->{extra}->{values}\n";
}
print "Object saved ok!\n",
"Object ID: $fb_id\n",
"Servings: $object->{servings}\n";
undef $obj;
my $new_obj = eval { My::ObjectClass->fetch( $fb_id ) };
if ( $@ ) {
die "Error found! ($@) Error information:\n",
"System Message: $ei->{system_msg}\n",
"Extra Stuff: $ei->{extra}->{sql}\n",
"$ei->{extra}->{values}\n";
print "Object fetched ok!\n",
"Object ID: $new_obj->{fatbomb_id}\n",
"Servings: $new_obj->{servings}\n";
# Uncomment the next line if you want to see the contents of the table
# after the test has run
$db->do( 'DROP TABLE fatbomb' );
$db->disconnect;
This is a really simple example and doesn't show
you security, the ability to write 'rulesets' which apply
logic across disparate objects, and more.
Currently there are only DBI 'drivers' for MySQL
and Sybase (ASE/ASA -- which also includes using MS SQL
Server thru DBD::ODBC), but others are very easy to write -- basically
just specifying how a DBD retrieves unique primary key
values (autoincrement, key pool, sequences, etc.) and
whether it knows how to quote data with a DBI SQL_TYPE hint.
Want to know more? Check out the
README
or
download the code.
|