[eluser]Vheissu[/eluser]
I'm currently in the process of developing an auth library that uses Datamapper Overzealous Edition to allow for a pretty feature packed auth class. One of the primary features of the class is that a user can be assigned to multiple roles.
So a user can be assigned to an admin role, user role, guest role and a moderator role. Or any of those, or all at the same time (if that makes sense). I've created a join table, and created my models a user model and role model that both have a $has_many defined both ways.
My issue is that when adding a new user, how am I able to assign a user to multiple roles when saving a new user object? Do I build an array and then iterate over it saving multiple times? Would appreciate some help on this. See below for what I have already.
Code:
public function create_user($login, $password, $fields = array(), $roles = array())
{
$login_type = config_item('auth.login_type');
if ($login_type == 'auto')
{
if (!valid_email(config_item('auth.login_type')))
{
$login_type = 'username';
}
else
{
$login_type = 'email';
}
}
$u = new User();
$u->where($login_type, $login);
$u->get();
if ( !$u->exists() )
{
$u->clear();
$salt = $this->generate_random();
$password = $this->create_password($this->generate_random(), $salt);
$u->{$login_type} = $login;
$u->salt = $salt;
$u->password = $password;
if (!empty($fields))
{
foreach ($fields AS $field => $value)
{
$u->{$field} = $value;
}
}
if (!empty($roles))
{
foreach ($roles AS $role)
{
// How do I have x amount of roles to this user?
}
}
}
}