How should I structure a piece of code that executes an operation, but may have slightly different behavior depending on, let's say, user roles?
Example: My app has a 'manager' and a 'employee' roles. There are many managers in my app, and each of them have many employees. I have a dashboard where managers and their employees can add/edit/delete products.
Both can edit the products the have created themselves, but managers can edit products belonging to his employees. If a manager edits a product created by an employee, the employee will get an email notification about the edit.
The issue I have, is that I´m creating if/else or switch/case statements for checking the user roles, and I feel once I add new roles my code will need to check for them too and my code will become harder to read.
For example:
// What I currently have:
public function updateProductForUser(Product $product, UserInterface $user)
{
$userWhoCreatedProduct = $product->getCreatedByUser();
if ($userWhoCreatedProduct === $user) {
// If the user who created the product is the same one trying to update it,
// then go ahead and execute the update.
$this->_doUpdateProductForUser($product, $user);
return;
} elseif ($user instanceof Manager) {
$allManagerEmployees = $this->someService->findAllEmployeesOfManager($user);
if (in_array($userWhoCreatedProduct, $allManagerEmployees)) {
// If the user trying to update the product is a manager, and the product was
// created by an employee of the manager, then execute the update but also
// send an notification to the employee that the product he created got updated
// by his manager.
$this->_doUpdateProductForUser($product, $user);
$this->notifyUserThatProductGotUpdated($product);
}
}
}
How can I improve this? Is there a better way? What are the pitfalls of the implementation? Any advice is very welcomed. Thanks!