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)?
Update
Here is the full code: http://laravel.io/bin/eDkmj
6
I think that break into 3 functions like you said is the best alternative, mainly to separate the logic of each user.
Here’s an example of how this can be made:
public function index() {
$method = "index" . ucfirst($this->user->role->name);
$this->$method();
}
private function indexAdmin() {
// do stuff
}
private function indexCustomer() {
// do stuff
}
private function indexManager() {
// do stuff
}
1