Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Object Oriented - Best way to implement multiple user roles

Tags:

oop

php

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 in a decent fashion, keeping in mind the type(s) of the user will define the kind of access they have in an application.

like image 277
Sabeen Malik Avatar asked Dec 08 '22 03:12

Sabeen Malik


1 Answers

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.

like image 130
devoured elysium Avatar answered Feb 18 '23 09:02

devoured elysium