Pathologically Eclectic Rubbish Lister | |
PerlMonks |
Re: How can I avoid creating two instances of the same objectby mattr (Curate) |
on Mar 02, 2006 at 16:15 UTC ( [id://533950]=note: print w/replies, xml ) | Need Help?? |
Hello,
It seems you have it slightly backwards from where I sit, since I would expect that User->new would return a new instance of a User object. my $newuser = User->new({name="matt"}); You should only make one database connection when your app runs and then everything uses that. The new method of each object should not be creating a new database handle. With Class::DBI anyway you wouldn't. Making a new object does not make a new database handle, it just points to the one you were using. You don't have to use Class::DBI as mentioned above, (i.e. you could just use DBI in the parent object) but that would be my way of doing it. For example you have WebApp::DBI (which is use base 'Class::DBI'). Then WebApp::User and WebApp::Company are both use base 'WebApp::DBI'. In WebApp::DBI I have a getdbh subroutine so all classes and objects inherit a ->getdbh method.
With this approach I believe you only need to use an object in a subroutine that needs it, otherwise the module is not loaded. Also objects inheriting from Class::DBI load columns lazily based on definitions of Essential columns. Also note that you can put generic retrieval code in the parent module (or in that parent's parent as with Class::DBI which provides the retrieve method) and then just do special cases in the child modules. Hope this helps. So bottom line is, for all this to be easily cleared up why not read the Class::DBI perldoc a few times and as rhesa notes you can get the db handle from its connection method or better yet as they recommend override db_Main with your own settings.
In Section
Seekers of Perl Wisdom
|
|