I created this class to keep track of a user's role:
class UserRoleHelper extends AppHelper { public $helpers = array('Session'); private $role = NULL; const CUSTOMER = 'customer'; const ASSOCIATE = 'associate'; const MANAGER = 'manager'; const ADMIN = 'admin'; const DEVELOPER = 'developer'; private $score = array( self::CUSTOMER => 0, self::ASSOCIATE => 1, self::MANAGER => 2, self::ADMIN => 3, self::DEVELOPER => 4, ); public function role() { if($this->role == NULL) { $this->role = strtolower($this->Session->read('Auth.User.role')) ?: 'customer'; } return $this->role; } private function is($role) { return $this->score[$this->role()] >= $this->score[$role]; } public function admin() { return $this->is(self::ADMIN); } public function manager() { return $this->is(self::MANAGER); } public function associate() { return $this->is(self::ASSOCIATE); } } The idea is to be able to have an expression like:
if($this->UserRole->manager()) { //do something } And have it evaluate true if you are a manager or higher (admin, developer).
I also tried to design it so if there is ever the need to add a level like GENERAL_MANGER = 3 which would shift the values of ADMIN and DEVELOPER up one, it won't effect anything.
I originally had the keys in the $score array as strings, but it seemed redundant when I had constants already defined with the same values. I have never seen an array definition with constants for keys in a class body before. I know variables are not allowed but it seems to work with constants. Still don't know if that is bad or not though.
Is there anything I have missed or can do to make this better?