开发者

PHP Object Oriented - Best way to implement multiple user roles

开发者 https://www.devze.com 2022-12-30 04:19 出处:网络
I have three types of users: A, B, C .. Hence a user base class and then we have 3 derived classes. However it is possible for a user to be of 2 types at the same time. How would we go about dealing w

I have three types of users: A, B, C .. Hence a user base class and then we have 3 derived classes. However it is possible for a user to be of 2 types at the same time. How would we go about dealing with this i开发者_如何学Cn a decent fashion, keeping in mind the type(s) of the user will define the kind of access they have in an application.


Maybe you should redefine your design. I'd say it'd be preferable to define two classes:

  • a Role class
  • an User class

An User class could then have a collection of roles. That will turn the whole design simpler and cleaner.

An User can have none, one or different roles. But an User is not intrinsically any of the roles it may have. It just has the ability of assuming a role.

But of course you can use the Decorator Pattern here, as stated by other poster.


I would use decorator pattern, e.g.

$user = new User ();
$user = new Role1 ($user);
$user = new Role2 ($user);


I would have had a look at the ACL class of the Zend Framework. Does a good job when it comes to have multiple roles for different users. There's also many articles and blogs discussing the use of the Zend ACL. More general about ACL: wikipedia - acl

Another way of dealing with different roles and permissions is Role-based access control: wikipedia - role-based access control

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号