I've been thinking about this for a little bit. My current context is in web programming, but I think this could be applied to a wider variety of programs.
What, in your opinions, is the best way to populate a list of objects from a database?
In the past, I've done things without classes at all, looking something like this:
while( @info = $sth->fetchrow_array ) { $f_name = $info[0]; $l_name = $info[1]; ... # do what is necessary with these variables. }
But it seems like there should be a separation of getting all of the information about what could be an object, and what to do with that information. One thought would be something like:
my @objects; while ( @info = $sth->fetchrow_array ) { my $object = Object->new(); $object->set_fname( $info[0] ); $object->set_lname( $info[1] ); ... # or my $object = Object->new( @info ); # or my $object = Object->new( fname => $info[0], lname => $info[1], ... ); push @objects, $object } for ( @objects ) { # do something with the object }
Another thought would be to create a sub to populate the objects for me. When I think about this, though, I think about two things, really...
@objects = Object::populate( "SELECT fname, lname, ... FROM object WHE +RE title='programmer'" )
@objects = Object::populate( title => "programmer" );
Maybe this is a bit of a meditation, but I'm definitely looking for some monks experienced in doing things like this to slap me with some wisdom, so let me know what you've done, and what you think is practically the best solution to populating a list of objects from a database. I'm sure there are some good ways to do this. I hope my question is clear. Thanks!
-Bryan
In reply to Best Practices: Populating Objects from Database by mrborisguy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |