Thursday, April 05, 2007

Dynamic delegation in PHP

While working on Pixelframe I devised 2 methods to dynamically delegate tasks to appropriate functions. These methods may already be known and used but these are mine and I thought it would be good to post them. These are particularly useful for handling requests where you call a certain function/script based on one parameter ( say 'action' ) and pass the rest of the parameters to the function /script. So here goes.

Delegation to functions in the same script

//the key for the action name in _POST
define("KEY_PARAM", "action");

//set up value=>funcToCall delegation array
//add new entries for each action=>function pair
$DELEGATES = array( "next"=>"nextImage",
"previous"=>"previousImage");


//check if the action we received from the request is defined
//check if the function is defined
if(array_key_exists($_GET[KEY_PARAM], $DELEGATES) &&
function_exists($DELEGATES[$_GET[KEY_PARAM]]))
{
//get the function string
$func = $DELEGATES[$_GET[KEY_PARAM]];
//remove this so it doesn't get passed to function, not really necessary
unset($_GET[KEY_PARAM]);

//call the function
call_user_func($func, $_GET);
}
else {
die("No such action {$_GET[KEY_PARAM]}");
}


Delegation to other scripts


When using this kind of delegation you should either decide a common function which IS implemented by all scripts or add your code to dynamically call the appropriate function ( say each function has the name the same as the script ).


//now replace funcToCall with script to include
$DELEGATES = array( "savechanges" => "save.php",
"changepassword" => "change_password.php",
"editpref" => "editpref.php" );

if(array_key_exists($_GET[KEY_PARAM], $DELEGATES)) {
//include the script
//assuming they are in the same directory
include_once($DELEGATES[$_GET[KEY_PARAM]]);
unset($_GET[KEY_PARAM]);
//here handler is the function
//now that the script is included, its available to us
handler($_GET);
}
else {
die("No such action {$_GET[KEY_PARAM]}.");
}


Well that covers it up. I hope it helps someone out there

No comments:

Post a Comment