|P is for Practical|
OO Perl: classes and database accessby fx (Pilgrim)
|on Sep 27, 2001 at 19:57 UTC||Need Help??|
fx has asked for the
wisdom of the Perl Monks concerning the following question:
First of all thanks to all those who replied to my previous posts of Using DBI: handlers or references to handlers? and OO Perl: calling a constructor within a class. After taking your advice my application is now maturing well.
I have come across a new dilemma however. My application has a number of users, and each user can control several projects. So I have a User class and a Project class.
There is a backend database to all this with user and project tables. I am struggling to find the best way to get the data out of the database and into the objects.
An example: users log into the system using login.pl. This takes a username, retrieves the user's details from the database and makes a new User object.
I have tried the following methods for populating the User object with the details:
- hardcode the SQL into login.pl, retrieve an array, and pass that array to the new() constructor of User
- write a class method for User which retrieves an array of data and calls the constructor
- write a new() constructor that queries the database
- write a Database package/class which contains several functions for retrieving values, which are then fed to a new() constructor for User
- write a User::Database class for specific user-type queries on the database
However, I'm confused as to the 'best' way to do this. Everytime I come up with a solution I seem to find a big problem with it. Another consideration I have is that as each user has several projects, then each User object has to have the capability to store an array of Project objects. Should I just do one big retrieve when I create a User object, or do I create the array of Project objects when needed? This confused me even more when writing the constructors.
Any pointers are most welcome.