http://www.perlmonks.org?node_id=1003845


in reply to OOP: How to construct multiple instances of a class at once

The short answer here is that it's your code and you can make any choice you like, though what you propose is certainly not standard OOP. You could naively add a loop to your new subroutine, like:
sub new { my $proto = shift(@_); my $class = ref($proto) || $proto; my @results; for my $userId (@_) { my $self = { "user_id"=> undef, "user_name" => undef }; bless ($self, $class); my $href = GETSQL("SELECT user_name FROM users WHERE user_ +id = $userId"); @{$self}{keys %{$href}} = values %{$href}; push @results, $self; } return @results; }
Except now you will break the code my $user = User->new($id) because you are returning an array in scalar context, and so your $user variable will contain the length of the array. You could address this with wantarray, but any time you reach for that you need to seriously consider if you are being too clever for your own good.

If I were in your situation, I'd probably leave the constructor alone, and use map if I really felt like I needed to get it done in one line:

my @users = map {User->new($_)} @userIds;

If you are having noticeable performance problems and have identified your database interaction as the source (see Devel::NYTProf), then you should optimize your database access. Rather than performing each query as a one-off, you can cache the connector and the query itself -- see prepare (or even prepare_cached) in DBI. Or post that bit of code, and we can critique for you.


#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.