Xajax 0.2: Tips and Tricks: Auto Register Methods
Xajax 0.2: Tips and Tricks: Auto Register Methods
This is handy if you have classes with lots of methods that need to be exported to xajax. Use this as a template for your class definition:
class MyClass {
/**
* A prefix for all ajax functions to aid automatic xajax registration
*/
private static $ajaxFuncPrefix = 'ax';
/**
* The xajax object
*/
public $xajax;
/**
* Do things
*/
public function __construct () {
$this->xajax = new xajax();
$this->registerFunctions();
}
/**
* Register all needed functions with xajax.
*
* All ajax function names must begin with self::$ajaxFuncPrefix, followed by
* an uppercase letter. They will be exported with that name, minus the prefix,
* and with the first letter in lowercase. So axFoo() would end up as the
* Javascript function xajax_foo()
*/
public function registerFunctions() {
$methods = get_class_methods($this);
foreach ($methods as $m) {
$p = self::$ajaxFuncPrefix;
if (preg_match("/^{$p}[A-Z]/", $m)) {
$m2 = preg_replace("/^{$p}([A-Z])/e", "strtolower('$1')", $m);
$this->xajax->registerFunction(array($m2, &$this, $m));
}
}
}
/**
* Do stuff
*/
public function axFoo () {
$response = new xajaxResponse();
...
return $response;
}
}
So, then on the client-side, you could just call xajax_foo();, and you don't need to update MyClass::registerFunctions() every time you add a method.