0

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

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 的建议,这是我为 register 方法提出的工作解决方案..

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);
            }
        }
    }
}

这似乎包括和注册对象现在绝对没问题,这个解决方案是否是一个“好”的解决方案,如果没有更多的输入或测试,我无法知道。

4

1 回答 1

2

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

 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;
     }
 }
于 2013-02-14T09:59:45.270 回答