Catalog Script: Catalog.pm

This module contains the logic for listing and fetching information about catalog entries.

package Catalog;
# modules/Catalog.pm
# Fetch items from the catalog and display them.

use strict;
use Carp;
use DBI;
use CGI qw(:standard);

# create new catalog object
sub new {
    my $class = shift;
    my $db = shift || croak "Please provide a DBI handle";
    return bless {'db' => $db},$class;
}

# return database handle (used internally)
sub db { return $_[0]->{'db'}; }

# Return list of catalog numbers.  In an array context, returns
# list of catalog numbers only.  In scalar context, returns a hash
# ref in which the keys are catalog numbers, and values are the
# brief descriptions ('names') of the items.
sub list {
    my $self = shift;
    my $db = $self->db || croak ('No database handle');
    my $sth = $db->prepare('SELECT catalog,name FROM ProductList') 
	|| croak("Prepare:",$db->errstr);
    $sth->execute || return;
    my %items;
    while (my($catalog,$name) = $sth->fetchrow_array) {
	$items{$catalog} = $name;
    }
    return keys %items if wantarray;
    return \%items;
}

# Get the information for an entry in the catalog.
# If successful, returns a hashref in which the keys are the column names.
# Returns the length of the image in a key named 'image'.  This can be used
# to determine if there is an image to display.
sub info {
    my $self = shift;
    my $catno = shift  || croak ("Provide a catalog number");
    my $db = $self->db || croak ('No database handle');
    my $sth = $db->prepare(<<END);
SELECT name,ProductList.catalog,price,description,length(image) as image
    FROM ProductList
	WHERE catalog=? 
END
    $sth->execute($catno);
    my $info = $sth->fetchrow_hashref;
    $sth->finish;
    return $info;
}

# Return the image data for an entry in the catalog.
sub image {
    my $self = shift;
    my $catno = shift  || croak ("Provide a catalog number");
    my $db = $self->db || croak ('No database handle');
    my $sth = $db->prepare('SELECT image FROM ProductList WHERE catalog=?');
    $sth->execute($catno) || return;
    my ($image) = $sth->fetchrow_array;
    $sth->finish;
    return $image;
}

1;
  


<< Previous
Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Sun May 2 16:08:03 EDT 1999