Josh
Josh

Reputation: 1804

Best way to handle multiple user groups with different data stored about them?

I'm creating a web application that will use multiple types of users (e.g. Admin, Managers, Users). Each user will require different pieces of information stored about them, some will be the same across each user type (i.e. username, password, email) and others will be different.

I'm wondering the best way to have the database, whilst using the ACL & Auth components in CakePHP. I see 2 possible solutions:

  1. Have three tables, one for each user type.
  2. Have five tables. A user table, a groups table, and then three tables containing the extra fields for each user type.

The problem I see with 1 is, I'm not sure how easy it is for CakePHP to use different models for permissions, instead of using a groups table. So, I think the second solution will be the easiest to set up, and maybe maintain, but is there too much overhead with the 3 extra tables? Or is there a better solution that I haven't thought about?

Upvotes: 2

Views: 657

Answers (1)

Wil
Wil

Reputation: 540

You could create a table that belongsTo User called user_data with the columns:

  • id
  • user_id
  • key
  • value

User HasMany UserData and UserData BelongsTo User

See http://book.cakephp.org/view/1043/hasMany and http://book.cakephp.org/view/1042/belongsTo for reference on how to setup relational data.

$data = array(
    'UserData' => array(
        'user_id' => 2,
        'key' => 'birthday',
        'value' => 'Oct 6th',
        'type' => 'admin'
    )
);

Then, in controller, you can fetch the custom data with Containable behavior:

$this->set('user', $this->User->find('first', array('conditions' => array('User.id' => 2), 'contain' => array('UserData'))));

In the view (Probably best to make this a helper function)

$birthday = Set::extract('/User/UserData[key=birthday]', $user);
echo $birthday[0]['value'];

Upvotes: 2

Related Questions