1. Home
  2. Computing & Technology
  3. Perl

Adding Object-Relational Mapping to your Perl Application - Part Two
Creating a Simple Rose::DB Object

by Kirk Brown
for About.com

Now that we have our database and our contacts table, it's time to create the actual Rose::DB object that goes along with it and brings all the functionality. At the most basic level, our Contact object is a simple configuration file. Let's take a look at it and go over each section individually:
package MyApp::Contact;

use MyApp::DB;

use base qw(Rose::DB::Object);

__PACKAGE__->meta->setup
(
table => 'contacts',
columns => [ qw(id name email) ],
pk_columns => 'id'
);

sub init_db { MyApp::DB->new }
First we set add this file to the MyApp package. If you haven't already figured it out, you'll be saving this in your MyApp directory as Contact.pm. Then you tell the interpreter that you're going to use the MyApp::DB file, which contains your database configuration and connection information.

The next part is where we get into the meat of the Rose::DB Object configuration - the __PACKAGE__->meta->setup function contains all the information that maps the table and fields to the actual object. The first option, table, is simply the name of the table that maps to the object. In this case, it is contacts. For all these tables and files, I like to use the singular version of the name of the object for the pm file, and the plural for the table name itself.

Next comes an array of the actual fields in the database. All you need here is the name of each of the column names and Rose::DB will take care of the rest. For the moment, we only have 3 fields, id, name and email. Finally, pk_columns identifies any primary key fields.

Once that is out of the way, we wrap the MyApp:DB->new function in the object's init_db subroutine so that our Contacts will know what database to use. Then we're ready to start creating and using our new Contact Rose::DB object!

Previous: Preparing our Database for Rose::DB

Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Working With Databases
  5. A tutorial on using Rose::DB and Rose::DB::Object to add Object-Relational Mapping to your Perl application.>

©2009 About.com, a part of The New York Times Company.

All rights reserved.