I hope this is the right board to post on, and I hope I'm not duping here. Apologies if I'm transgressing, but here goes!
I'm trying to model objects with many-to-many relationships. One object is 'group', and one object is 'user'. Just like in the UNIX world, one user can belong to many groups, and one group can contain many users. Modelling that in my database was easy; I just created a junction table. But I came up against a rock wall when I started to model them in PHP:
class User {
var $id, $username, $password;
var $groups = array ();
function User () {
}
function create ($username) {
global $conn;
$recordSet = &$conn->Execute('SELECT * FROM users WHERE username = ' . $username);
$this->username = $recordSet->fields['username'];
$this->password = $recordSet->fields['password'];
$recordSet = &$conn->Execute('SELECT g.groupname AS groupname FROM usersToGroups ug, groups g WHERE ug.groupID = g.id');
$i = 0;
while (!$recordSet->EOF) {
$this->groups[$i] = new Group;
$this->groups[$i]->create ($recordSet->fields['groupname'];
$recordSet->MoveNext();
$i ++;
}
}
}
class Group {
var $id, $groupname;
var $users = array ();
function Group () {
}
function create ($groupname) {
global $conn;
$recordSet = &$conn->Execute('SELECT * FROM groups WHERE groupname = ' . $groupname);
$this->groupname = $recordSet->fields['groupname'];
$recordSet = &$conn->Execute('SELECT u.username AS username FROM usersToGroups ug, users u WHERE ug.userID = u.id');
$i = 0;
while (!$recordSet->EOF) {
$this->users[$i] = new User;
$this->users[$i]->create ($recordSet->fields['username'];
$recordSet->MoveNext();
$i ++;
}
}
}
(these two classes are dramatically simplified from the originals, just for the sake of brevity. Also of note is that I'm using ADODB; $conn is an already instantiated ADODB class.)
Sooooooo... the problem here is that using this set of data:
user 'steve' belongs to groups 'admin', 'users', 'editors'
group 'editors' contains users 'rachel', 'steve', 'pete'
Instantiating a User using create('steve') will grab Steve's groups and instantiate them as Group objects, including the 'editors' group, which will in turn end up instantiating a User named 'steve', who will instantiate a Group named 'editors', and so on ad infinitum.
Any comments or suggestions on how I could best model this? Right now User->groups is just an array containing strings instead of Group objects, and Group->users is the same. That way, new objects can be instantiated at will without creating a cascade of new objects. But it seems to me that there should be a more 'OOP pure' way of doing this...
Thanks in advance!
Paul d'Aoust