Search code examples
phpcode-organization

stuck in a rut, need help breaking through to the next level


I'm working on a humble website with my mediocre, self-taught PHP skills, and the current interface structure is like this:

<?php
  if (A) {
    $output = someFunc(A);
  } else if (B) {
    $output = anotherFunc(B);
  } else if (C) {
    $output = yetAnotherFunc(C);
  } else {
    $output = 'default stuff';
  }
?>
<html template top half>

<?php echo $output; ?>

</html template bottom half>

This worked ok at first, and seemed pretty well organized, but the functionality required has grown by a factor of 10 and it's rapidly turning into an unmaintainable, embarrassing mess and I don't know how to get out of it.

I feel that the functions being called for each situation are fairly well-written and focused, but am at a loss as to how to handle the middle-step between the user and the functions that creates the layout and handles the return.

I have a feeling that MVC is one solution? But I'm having a hard time grasping how to go from here to there...

I apologize for any headaches or unpleasant memories the above code may have prompted. Thank you for your time.


Solution

  • You seem to have started the way a lot of people do, a big if and/or case statement that continues to grow. All those "if" checks can take time. MVC is definitely a great way to go, but there are so many ways to implement it. I would recommend also looking to the Front Controller design pattern, which is commonly used with MVC.

    One way to change how you are doing things is to switch to a defined list of "actions" using an associative array. And change your functions into includes. Then you can have multiple functions, variables and other processing code.

    $actions = array(
    'A'=>'action1.php',
    'B'=>'action2.php',
    'C'=>'action3.php',
    'default'=>'action_default.php'
    );
    if ( isset( $actions[ $_GET['action'] ] ) ) {
        include( $actions[ $_GET['action'] ] );
    } else {
        include( $actions['default'] );
    }
    

    Then your "index" file is just a routing tool, which is pretty much the Front Controller concept.