...

View Full Version : spl_autoload_register help?



Oatley
11-06-2012, 10:04 PM
Hello, I have a class that uses the reflection class that Fou-Lu kindly helped me with to load storage drivers like so




//Include all the files that might be needed
include_once 'mysql.class.php';
include_once 'pdo.class.php';
include_once 'xml.class.php';
//etc

class Connection {
public static function createConnection($type) {
$driver = $type . 'Driver';
if (!class_exists($driver)) {
throw new Exception('No drivers for storage type: ' . $type);
}
$ref = new ReflectionClass($driver);
return $ref->getMethod('Connection')->invoke(NULL);
}
}



But rather than including ALL the drivers that I might need before I access my class I wanted to make use the spl_autoload_register feature to load the drivers as and when they are needed.

Is this possible with the above, as I don't get how to do it? As it would be trying to use the spl_autoload_register to load the ReflectionClass each time, as it loads the class name rather than the $type passed in I would have thought?

Is there a way around this? Or any type of other solution?

Thank You

Fou-Lu
11-07-2012, 03:24 PM
Yeah, you can use an autoload to do this. But since your class files don't match your class names, you'll need to strip the 'Driver' name off of it in order to find it.



function driverLoader($sDriver)
{
if (!class_exists($sDriver))
{
$sClass = str_ireplace('Driver', '', $sDriver);
require_once $sClass . '.class.php';
}
}

spl_autoload_register('driverLoader');



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum