vendredi 28 novembre 2014

How to avoid switches?


I use Laravel as a PHP framework, although the question is not exactly about laravel, more about structuring controller methods.


I have a route to orders page. Depending on the user role I need to include different views and I have different logic for each role. It looks like this:



public function index()
{
switch ($this->user->role->name) {
case 'admin': {
// Some code
break;
}
case 'customer': {
// Some code
break;
}
case 'manager': {
// Some code
break;
}
}
}


I repeat this pattern for all routes which are accessible for many roles. I know that using repeatedly if/else, switch or this kind of stuff is not the best solution. Also the function becomes quite big (not much but depends on logic). Of course I can break it into 3 subfunctions lie (indexAdmin, indexManager, indexCustomer) but am still not sure if it's good.


Could anybody explain how to deal with it, preferably using Laravel (I use 5 dev version)?





Aucun commentaire:

Enregistrer un commentaire