punkish has asked for the wisdom of the Perl Monks concerning the following question:
This is how I want my design to be -- the object constructor gets a couple of input values, and creates a fully populated object. There are three things to consider:
# In my long running program my $dbname = get_db_name_from_some_config_file(); my $dbh = DBI->connect("dbi:SQLite:dbname=$dbname","",""); my $user_id = 1; my $cfg = get_user_specific_config_values_stored_in_db($user_id); for my $obj_id (0 .. 2 million) { my $obj = new Obj(dbh => $dbh, cfg => $cfg, obj_id => $obj_id); $obj->very_long_complicated_program(); } # In a nearby module Obj.pm sub new { my ($class, %args) = @_; my $dbh = $args{dbh} my $cfg = $args{cfg}; my $obj_id = $args{obj_id}; my $in = { dbh => $dbh, cfg => $cfg, foo => {}, bar => {}, }; my $self = bless $in, $class; # foo is a result of a different query for every obj_id $in->{foo} = $self->foo($obj_id); # The following part is the only part I am still confused about. # Should I use something like Memoize here? # # bar changes only once per, say, every 5000 objects, # and the resulting query from $self->bar is a very # large set (thousands of rows), so it makes sense to # query the db only when bar changes. So, for obj_id # 0 through 4999, bar remains the same, then for obj_id # 5000 through 9999 a new bar is returned, and so on $in->{bar} = $self->bar($obj_id); return $self; } sub dbh { my $class = shift; return $self->{dbh}; } sub cfg { my $class = shift; return $self->{cfg}; } sub foo { my ($class, $obj_id) = shift; my $cfg = $self->cfg; my $dbh = $self->dbh; my $foo = query_dbh_for_foo_execute($obj_id); $foo = change_parts_of_foo_based_on($cfg); return $foo; } sub bar { my ($class, $obj_id) = shift; my $dbh = $self->dbh; my $bar = query_dbh_for_bar_execute($obj_id); $bar = change_parts_of_bar_based_on($cfg); return $bar; }
How do I go about implementing the above?
Update2: Another, possibly better way to ask my question -- how do I create an object a part of which (its data) is shared with other objects without requiring making a copy of that data?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: initializing objects from values from a db
by CountZero (Bishop) on Dec 05, 2009 at 20:19 UTC | |
by punkish (Priest) on Dec 05, 2009 at 20:29 UTC | |
|
Re: initializing objects from values from a db
by punkish (Priest) on Dec 06, 2009 at 04:29 UTC |