所以我在 PHP 中有一个不断增长的系统,我有一个静态类来处理数据库连接的东西。
<?php
class Database {
// ... connection upon construction and ways of escaping the data
public function query($query) {
// performs query and returns the data.
}
}
class API { // Not actually called api, but for the purposes of this
private static $database = false;
public static function GetDatabase() {
if (static::$database === false) {
static::$database = new Database(connection information)
}
return static::$database;
}
}
?>
我还有很多执行特定功能集的“控制器”或数据库适配器。
<?php
class UserDBAdapter {
public function newUser($info) {
// validates and builds the query statements
API::GetDatabase()->query($query);
}
}
?>
所以真正的问题是我在代码中到处都需要 UserDBAdapter。在几个不同的文件中说,可能在其他控制器中,我不想将它作为变量传递(当每个方法都有它时它会变得烦人)。我也不想创建 2 个这样的对象(出于速度目的)。
那么我可以做一些与我对 $database 对象相同的事情吗?在调用它们之前我不会初始化它们,这应该是有效的,并且无论范围如何,它们都不需要在整个过程中重新创建。至少这就是我开始这个想法的原因,但我不知道它是否是最好的想法。
谢谢