2

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!

neph
  • 733
  • 1
  • 8
  • 16
  • You would use `isset()` in place of `in_array()`. And the speed difference of a hash map over a switch is [possibly even measureable](http://xdebug.org/docs/profiler). – mario Jan 28 '12 at 16:29

2 Answers2

2

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

Community
  • 1
  • 1
kba
  • 19,333
  • 5
  • 62
  • 89
  • I am all for doing that, however the reason I have not done that is this: http://pooteeweet.org/blog/538 , I don't know how true that is to this day, but isn't it true that with __autoload you are basically out of luck with apc and similar opcode caches? – neph Jan 28 '12 at 16:46
  • @neph Nope, APC will work just fine. See http://stackoverflow.com/a/1396538/453331 – kba Jan 28 '12 at 16:53
  • `__autoload()` is "a kind of" deprecated. You should use `spl_autoload_register()`, which works quite similar and (at the end) does exactly the same. – KingCrunch Jan 28 '12 at 17:01
0

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

Mark Baker
  • 209,507
  • 32
  • 346
  • 385