Domanda

I have a basic User model that satisfies all the needs of a generic user. I now need to create several different roles for the user, each with about 10-20 different methods that are unusable by the other roles.

Assume that I have to load the generic User class to determine the user's role...

Since it's inefficient and heavy to package so many different role-based methods into the generic User model (when they can't be utilized by all roles), what is the best way to give user's access to their role-based methods ONLY when they need them?

Here are some ideas I'm tossing around:

  1. Have a separate class of services per role, and give them to the User class according to the user's role

  2. Simply lug around all the methods in the user class, and only allow access to each when the user has the correct role.

  3. Totally refactor and make the role based classes inherit from the User class.

Are any of these good ideas, or is there a better idea at all?

È stato utile?

Soluzione

Why not just composition the role based classes into the User object?

$user = new User(/* pass role as an arg */);

// Internally:
// if ($user->getRole() instanceof AdminRole) or similar...
if ($user->isAdmin()) {
    // AdminRole::doSomethingAdminish()
    $user->getRole()->doSomethingAdminish();
}

Altri suggerimenti

Take a look at the factory pattern. Essentially, you pass it the data required to instantiate the object, and it returns the correct object in a ready to use state.

Perhaps something like

class UserFactory
{
   public static function getUser($userId)
   {
      $user = new User($userId);
      switch ($user->getType()) {
         case 'admin' :
            return new AdminUser($user);
         case 'guest' :
            return new GuestUser($user);
         default :
            //handle 
      }
   }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top