Ok Ninja ... here is some code that is using the method Jason provides to allow parameter lists. As an alternative we might just want to pass an array to the register() method (e.g. $registry->register('Test', array('foo', 'bar', 'baz')); ) as it might allow passing objects by reference in PHP4 -- people can give their opinions on this.
I first learned this multi-parameter code (as Jeff and Jason probably did) from Lastcraft. This is probably one of the few cases where eval() is tolerated.
I also swapped out you hard coded paths and extensions for settable properties -- so with the constructor you can get the settings you like and others can use theirs. It defaults to no path and just a '.php' file extension.
Code: Select all
<?php
class Registry{
var $instances;
var $args;
var $path;
var $prefix;
var $suffix;
function Registry($path='', $prefix='', $suffix='.php') {
$this->path = $path;
$this->prefix = $prefix;
$this->suffix = $suffix;
}
function register($name /*, $arg1, $arg2 ... */) {
if (func_num_args() > 1) { // args were passed
$this->args[$name] = func_get_args();
array_shift($this->args[$name]); // remove $name for args array
}
}
function &get($name) {
if (! isset($this->instances[$name])) {
if (! class_exists($name)) {
include($this->path . $this->prefix . $name . $this->suffix);
}
$arglist = array();
if (isset($this->args[$name])) { // there are args
$n = count($this->args[$name]);
for ($i=0; $i<$n; ++$i) {
$arglist[$i] = "\$this->args['$name'][$i]";
}
}
eval("\$this->instances['$name'] =& new {$name}(" . implode(', ', $arglist) . ');');
}
return $this->instances[$name];
}
}Code: Select all
class Test {
var $one = 'NOT SET';
var $two = 'NOT SET';
var $three = 'NOT SET';
function Test($one, $two, $three) {
$this->one = $one;
$this->two = $two;
$this->three = $three;
}
}
$registry =& new Registry(CORE_INCLUDE_PATH, 'classes/', '.inc.php');
$registry->register('Test', 'foo', 'bar', 'baz');
$test =& $registry->get('Test');
echo '<pre>' . print_r($test, 1) . '</pre>';