PHP在类中自动加载帮助程序


PHP autoloading helpers inside a class

我目前有一个手动方法将助手注册到我的基本连接类中,大致如下:

class db_con
{
    // define the usual suspect properties..
    public $helpers; // helper objects will get registered here..
    public function __construct()
    {
        // fire up the connection or die trying
        $this->helpers = (object) array();
    }
    public function __destruct()
    {
        $this->helpers = null;
        $this->connection = null;
    }
    // $name = desired handle for the helper
    // $helper = name of class to be registered
    public function register_helper($name, $helper)
    {
        if(!isset($this->helpers->$name, $helper))
        {
            // tack on a helper..
            $this->helpers->$name = new $helper($this);
        }
    }
    // generic DB interaction methods follow..
}

然后是一个助手类,如.

class user_auth
{
    public function __construct($connection){ }
    public function __destruct(){ }
    public function user_method($somevars)
    {
        // do something with user details
    }
}

因此,在创建了$connection对象之后,我会手动注册一个助手,比如:

$connection->register_helper('users', 'user_auth');

现在我的问题是,我能以某种方式在基本连接类中自动加载助手类吗?(在register_helper()方法或类似方法中)还是我只能手动或通过某种形式的外部自动加载器加载它们?

如果这个问题在其他地方得到了回答,我很抱歉,但我只是没有找到它(不是因为缺乏尝试),我还没有任何真正的自动加载经验。

非常感谢任何帮助或建议,提前感谢!:)

编辑:根据Vic的建议,这是我为注册方法提出的工作解决方案。。

public function register_handlers()
{
    $handler_dir = 'path/to/database/handlers/';
    foreach (glob($handler_dir . '*.class.php') as $handler_file)
    {
        $handler_bits = explode('.', basename($handler_file));
        $handler = $handler_bits[0];
        if(!class_exists($handler, false))
        {
            include_once $handler_file;
            if(!isset($this->handle->$handler, $handler))
            {
                $this->handle->$handler = new $handler($this);
            }
        }
    }
}

这似乎包括并注册了对象,目前来说非常好,无论这个解决方案是否"好",如果没有更多的输入或测试,我都不知道。

代码可能如下所示,但为什么需要它?

 public function register_helper($name, $helper)
 {
      if(!isset($this->helpers->$name, $helper))
      {
           $this->load_class($helper);
           // tack on a helper..
           $this->helpers->$name = new $helper($this);
      }
 }
 private function load_class($class) 
 {
     if( !class_exists($class, false) ) {
          $class_file = PATH_SOME_WHERE . $class . '.php';
          require $class_file;
     }
 }