Avoid large switch statement in frontcontroller

468 views Asked by At

I have a larger application with a Frontcontroller in php that handles incoming ajax requests. I am thinking about a good way to handle Action->Method mapping, this controller is in charge of instantiating other classes and executing methods there.

The switch is just getting too big and it's ugly. I was thinking about creating an array and simply doing:

if(in_array($action, $methodmap)){
  $methodmap[$action]();
}    

But not sure of how efficient that would be or if there are any other better alternatives, performance is important since this controller handles a whole lot of incoming requests.

Thanks!

2

There are 2 answers

3
kba On BEST ANSWER

You could create a simple routing system.

index.php

<?php

class InvalidClassException extends Exception {}
function autoloader($class)
{
    $path = 'controllers/'.$class.'.php';
    if (!ctype_alnum($class) || !file_exists($path))
        throw new InvalidClassException("Couldn't find '$class'");
    require($path);
}
spl_autoload_register('autoloader');

$request = isset($_GET['request'])?$_GET['request']:'front';
$controller = new $request();
$controller->index();

And a directory controllers/ where you store all your controllers. E.g.

controllers/test1.php

<?php

class Test1
{
    public function index()
    {
        print "Test 1";
    }
}

When accessing index.php?request=test1, Test1->index() would be called, thus output

Test 1

0
Mark Baker On

TRy using a "routing" configuration file instead... that way, you can add new routings to the application without needing to change the actual action/method mapping code