# In my script my $dbh = DBI->connect(); my $id = 1; my $obj = Obj->new($dbh, $id); my $foo = $obj->foo; my $bar = $obj->bar; # In a nearby package package Obj; use constant PI => 3.14; use constant G => 9.81; my %foo_cache; my %bar_cache; sub new { my ($class, $dbh, $id) = @_; my $self = bless {}, $class; $self->{dbh} = $dbh; $self->{id} = $id; return $self; } sub dbh { my $self = shift; return $self->{dbh}; } sub id { my $self = shift; return $self->{id}; } sub foo { my $self = shift; my $id = $self->id; my $dbh = $self->dbh; unless ($self->{foo}) { # check if foo is in cache if (exists $foo_cache{$id}) { # return from cache $self->{foo} = $foo_cache{$id}; } else { $foo_cache{$id} = PI * query_foo_from_db_using($dbh, $id); $self->{foo} = $foo_cache{$id}; } } return $self->{foo}; } sub bar { my $self = shift; my $id = $self->id; my $dbh = $self->dbh; unless ($self->{bar}) { # check if bar is in cache if (exists $bar_cache{$id}) { # return from cache $self->{bar} = $bar_cache{$id}; } else { $bar_cache{$id} = G * query_bar_from_db_using($dbh, $id); $self->{bar} = $bar_cache{$id}; } } return $self->{bar}; } 1; #### package Obj; use constant PI => 3.14; use constant G => 9.81; my %foo_cache; my %bar_cache; use parent ('Obj::Foo', 'Obj::Bar'); sub new { my ($class, $dbh, $id) = @_; my $self = bless {}, $class; $self->{dbh} = $dbh; $self->{id} = $id; return $self; } sub dbh { my $self = shift; return $self->{dbh}; } sub id { my $self = shift; return $self->{id}; } 1; ############### package Obj::Foo; sub foo { my $self = shift; my $id = $self->id; my $dbh = $self->dbh; unless ($self->{foo}) { # check if foo is in cache if (exists $Obj::foo_cache{$id}) { # return from cache $self->{foo} = $Obj::foo_cache{$id}; } else { $Obj::foo_cache{$id} = Obj::PI * query_foo_from_db_using($dbh, $id); $self->{foo} = $Obj::foo_cache{$id}; } } return $self->{foo}; } 1; #### ############### package Obj::Bar; sub bar { my $self = shift; my $id = $self->id; my $dbh = $self->dbh; unless ($self->{bar}) { # check if bar is in cache if (exists $Obj::bar_cache{$id}) { # return from cache $self->{bar} = $Obj::bar_cache{$id}; } else { $Obj::bar_cache{$id} = Obj::G * query_bar_from_db_using($dbh, $id); $self->{bar} = $Obj::bar_cache{$id}; } } return $self->{bar}; } 1;