Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want to add some of my own functions to a BerkeleyDB object. i.e. use 'connect' to include all my favorite configurations to initialize a BerkeleyDB and some other functions to some specific data sources. i.e.

my $db_obj = MyApp::BerkeleyDB->connect("dbname.db"); .... # then I can use BerkeleyDB internal methods $db_obj->db_put('key', 'value'); .... # use my own functions.. $db_obj->myfunc("src", ...); ....

I guess subclassing is the best way to do this. but I am not an OO-guy so far, and not sure how to handle it. trying $class->SUPER is not working. (Apparently, I dont know how to subclass yet:(((). Can anyone help me or give me a hint on this issue, many thanks

package Myapp::BerkeleyDB use warnings; use strict; use base 'BerkeleyDB'; use BerkeleyDB; # the following code apparently not working!!! sub connect { my ($class, $dbname) = @_; return new BerkeleyDB::Btree -Filename => $dbname, ...... or undef; }

ttg

Replies are listed 'Best First'.
Re: ??Best way to subclass BerkeleyDB
by Corion (Patriarch) on Jul 17, 2008 at 20:01 UTC

    Personally, I would avoid inheritance in favor of delegation:

    package MyApp::BerkeleyDB; use strict; use BerkeleyDB; use vars '%bdb_defaults'; %bdb_defaults = ( Filename => 'foo', ... ); sub new { my ($class,%args) = @_; my $self = \%args; bless $self, $class }; sub db { $_[0]->{db} }; sub connect { my ($class,%args) = @_; %args = (%bdb_defaults, %args); my $db = BerkeleyDB::Btree->new(%args); $class->new( db => $db ); };
Re: ??Best way to subclass BerkeleyDB
by Joost (Canon) on Jul 17, 2008 at 20:03 UTC
    return new BerkeleyDB::Btree -Filename => $dbname, ......
    That's wrong. The way calling a constructor from a subclass works in perl is to pass on the $class argument to the superclass's constructor, like this:
    return $class->SUPER::new( ... )
    Which should make sure the final object will be in the $class class (which will contain the actual requested class - IOW your class, or some subclass of that), instead of the BerkelyDB::Btree class (provided its constructor is coded correctly)

Re: ??Best way to subclass BerkeleyDB
by moritz (Cardinal) on Jul 17, 2008 at 20:08 UTC
    If you work with BerkeleyDB::Btree objects, I think you should subclass that, not BerkeleyDB itself. Then you'd write something along these lines:
    package Myapp::BerkeleyDB use warnings; use strict; use BerkeleyDB; use base 'BerkeleyDB::Btree'; sub connect { my ($class, $dbname) = @_ return $class->SUPER::new( -Filename => $dbname, ... ) }

    But note that I'm not familiar with BerkeleyDB, and the code is not tested.