Mark
Mark

Reputation: 183

PHP OOP save instance of object in instance or only the id?

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?

Upvotes: 2

Views: 378

Answers (2)

Leri
Leri

Reputation: 12535

This is typical has-a relationship between User and UserGroup. In another words User has a UserGroup. So I think class User should have reference to UserGroup. If you are too worried and/or limited in resources you can create instance of UserGroup in User when it's actually needed.

The implementation will be something like:

class User
{
    private $userGroupId;
    private $userGroup = null;
    public function setGroupId($userGroupId)
    {
        $this->userGroupId = $userGroupId;
    }

    public function getGroup()
    {
        if ($this->userGroup === null)
        {
            $this->userGroup = new UserGroup($this->userGroupId);
        }
        return $this->userGroup;
    }
}

Upvotes: 3

kitti
kitti

Reputation: 14794

This is a somewhat complex problem to solve, but the short answer is both. The database itself can only store a user group ID, but your model should have both. The user group ID should be pulled from the database, and you can use PHP magic __get and __set methods to load the UserGroup model on access and save the ID from a UserGroup model on commit.

You can also use a static array in the UserGroup class to hold all hydrated UserGroup models, so if the same model is requested more than once the same instance can be returned.

EDIT: As Del Pedro pointed out in the comments, this has been done before (ORMs) and you should take advantage of that if it benefits you.

Upvotes: 0

Related Questions