<?xml version="1.0" encoding="windows-1252"?>
<node id="1003841" title="OOP: How to construct multiple instances of a class at once" created="2012-11-14 10:50:09" updated="2012-11-14 10:50:09">
<type id="115">
perlquestion</type>
<author id="1003821">
DrGTO</author>
<data>
<field name="doctext">
Hi there monks,
this is my first post, so please forgive any foolish behaviour.

I am not a perl newbie but I am trying out some OOP stylish programming.

I have a user class, which is loaded with values from a database.
So, whenever I create a new user object I have one corresponding MySQL query for the user data.

Now, I have the situation, that I would like to get all users in the system.
Using a loop
&lt;code&gt;
my @users;
foreach my $id (@userIds) {
       push (@users,User-&gt;new($id));
}
&lt;/code&gt;
this will produce one MySQL query per object initialisation. So many queries for a longer user list ...
I am wondering, if there is a way to use the class constructur with a list of ids, running only one query in the new() constructur and then return several user objects at once?

Something like:
&lt;code&gt;
my @users=User-&gt;new($id1,$id2,$id3,$id4);
&lt;/code&gt;

Where array @users() contain several user objects afterwards.

My class constructor looks like
&lt;code&gt;
sub new {
	my $proto = shift(@_);
	my $userId=shift(@_);
        my $class = ref($proto) || $proto;
	my $self = {
		"user_id"=&gt; undef,
		"user_name" =&gt; undef
        };
        bless ($self, $class);
	my $href = GETSQL("SELECT user_name FROM users WHERE user_id = $userId");
	@{$self}{keys %{$href}} = values %{$href};
        return $self;
&lt;/code&gt;

All vague solutions I can think of, mean a huge reconstruction of code. E.g. different constructors for single / multiple instances nested within the class....

Any help, comments are appreciated.
Thanks!!</field>
</data>
</node>
