A giant elseif chain, a giant switch or a tiny switch with features?

I have a 9000 line PHP file that consists of about 30 discrete areas moved through variables $_POST. So maybe ...

elseif (isset($_POST['view_user']) 
     || isset($_POST['edit_user']) 
     || isset($_POST['process_user_status']))

... etc. I probably have about 75 entry points in these thirty areas, all of which are handled by long chains of elseif isset, as mentioned above.

I was thinking about changing this to something more normal. Ideas I came up with so far:

1) Fold the columns to boolean and use them in the elseif chain. Thus, the above will be reduced to elseif ($area_user), and $area_userwill be set to trueif any of the $_POSTabove were installed . But this does not apply to the problem of complexity.

2) Use cases instead of elseif. So the above will be ...

case (isset($_POST['view_user'])):
case (isset($_POST['edit_user'])):
case (isset($_POST['process_user_status'])):
    do stuff;
    break;

But then again, while it removes the elseif syntax, it just replaces it with something that, being a little more manageable, can still hide the true problem.

3) Use functions. Therefore, at the top of the page I have a similar switch statement, but instead of being in the middle of the page going directly to the script area, it calls the function, so instead of “doing things” it can call UserArea($_POST['whatever']). This has the advantage of moving all variables $_POSToutside the meat script and concentrating them on navigation and functional calls. However, this will require a lot of declarations of global functions, which I do not currently need, because elseif branches are in the global scope.

4) MVC, .. , . , , .

, 3, , , , . ?

+3
1

: .

$_POST ('view_user' ..) , (), . ifelse $_POST, .

, . MVC ( , ).

// Untested, but something like this
$handlers = array(
  'view_user' => 'UserArea',
  'edit_user' => 'UserArea',
  'view_document' => 'DocManagement', // for example
  // etc...
);
foreach ($_POST as $key => $value) {
  if(array_key_exists($key, $handlers)){
    call_user_func($handlers[$key]);
  }
}
+2

Source: https://habr.com/ru/post/1793637/


All Articles