I am a little bit confused how to implement the following OO structure in PHP. I have a class ‘User‘ and a class ‘UserGroup‘ a ‘User’ is part of one ‘UserGroup’. In the database the user table has a field ‘user_group_id‘. What is a good and ‘server friendly’ way of implementing this? Do I create an instance of UserGroup inside my user class or do i only save the user_group_id in a variable?
Note: not all methods are shown in the examples.
Option 1
class User
{
private $userGroupId;
public function setGroupId($userGroupId)
{
$this->userGroupId = $userGroupId;
}
}
Option 2
class User
{
private $userGroup;
public function setGroup($userGroupId)
{
$this->userGroup = new UserGroup($userGroupId);
}
}
My problem with option 2 is that it might consume more server resources because it creates a totally new instance of a usergroup for every user. But I am not sure about this and I can’t find any info about this.
My question: what is good implementation?
This is typical has-a relationship between
UserandUserGroup. In another wordsUserhas aUserGroup. So I think classUsershould have reference toUserGroup. If you are too worried and/or limited in resources you can create instance ofUserGroupinUserwhen it’s actually needed.The implementation will be something like: