I’ve built an abstract User class which is extended by Admin, Manager, and Employee. User contains everything that all Users will need, and abstracts everything that each user handles using different logic based on the instance. My confusion comes in when I have functionality that an Admin or Manager class will handle the exact same way, but an Employee won’t be able to access at all.
For example, managing a user other than itself should be restricted to only Admins and Managers while an Employee should never be able to do this. I want to avoid copy/pasting the exact same logic in both the Admin and Manager class, so should I make a single private function and move it up to the User class and simply have the Admin/Manager classes call it from there?
abstract class User
{
public $username;
public $userId;
public $company;
public $error;
private function updateUser($user)
{
// Logic for saving the user info
}
....
}
class Admin extends User
{
public function updateUser($user)
{
parent::updateUser($user)
}
....
}
class Manager extends User
{
public function updateUser($user)
{
parent::updateUser($user)
}
....
}
class Employee extends User
{
public function updateUser($user)
{
$this->error = "Invalid Permissions";
}
....
}
Should this be handled differently? Thanks.
You could move the logic into the User base class with a check to ensure that the specified user is either a manager or admin, but you could add different ‘classes’ of users at a later date which may need the same functionality, in which case the code you wrote will need to be updated.
My suggestion would be a new abstract class that sits in between the Manager/Admin users and the User abstract class, maybe something like
UserEditor.UserEditorextends User and provides the functionality for Admin/Managers to update other users, and Admin/Managers extend from UserEditor instead of your User class.