2012/02/27

a driver on-demand loader

here's a bit of a trick:

if you work with a driver model (where your framework uses drivers to handle certain aspects of the framework, ie. database connectivity, session, authentication etc.), but you want to initialize drivers on demand instead of initializing them on every run regardless of whether they're needed, you can do it with a bit of a trick.

here is an example:

<?php
class realClass1 {
 public function hop() {
  print "really hop hop hop!<br/>\r\n";
 }
}

class realClass2 {
 public function hop() {
  print "really bum ban beng!<br/>\r\n";
 }
}

class dummyClass {
 private $which;
 private $class;
 public function __construct($drvname,$rclass) {
  $this->which = $drvname;
  $this->class = $rclass;
 }
 public function __call($method,$params) {
  print "loading driver for {$this->which}: {$this->class} for method {$method}<br/>\r\n";
  $GLOBALS['drivers'][$this->which] = new $this->class();
  return(call_user_func_array(array($GLOBALS['drivers'][$this->which],$method), $params));
 }
}

$drivers = array('bam'=>new dummyClass('bam','realClass1'),'bim'=>new dummyClass('bim','realClass2'));

$drivers['bam']->hop();
$drivers['bam']->hop();
$drivers['bim']->hop();
$drivers['bim']->hop();

?>

it's a bit primitive, but it illustrates the point. of course, most drivers would have to be initialized before using any methods on them, but you can do that in the magic __call method. essentially, since objects are pointed at using references, what a dummy driver needs to do is catch all method calls to the dummy driver, and then get the real driver up and running, but what is most important, replace the reference that points to it by the real driver object reference. it's that easy.

No comments:

Post a Comment