我有大量的课程:主论坛类,论坛板类和线程类。这些可以被认为是我网站上下文中的模型。
以前的Web开发人员使用的设置在每个类中创建了一个新的mysqli连接,并在类的实例化时连接。这意味着在threads页面中有3个不同的论坛,线程和用户连接。这显然不理想,我认为甚至不是最佳的。
我参与了一个以前的项目,我可以简单地将数据库类的新实例传递给我正在使用的类,但这并不理想,因为我需要实例化多个类并将数据库实例传递给每个上课会打败这个目的。
在每个类中,都会进行数据库调用,因此每个类中都需要数据库对象/实例,而不必在不同时间实例化它。
例如,在线程类中,您可以:
function get_threads($board_id) {
return $this->con->query("some query");
}
有谁知道如何实现这个目标?
答案 0 :(得分:3)
我更喜欢一个可以从工厂模式中获取数据的数据库控制器。在下面的示例中,您可以创建一个控制器,让组件根据需要使用它。
ex: $threads = new ThreadClass($mysqlConnection);
我希望这会有所帮助
# 1. mysql source or "socket" using PDO
class SimpleDatabaseSocket {
protected static $dbh = false;
public function connect($database, $user, $pass, $host) {
$dsn = "mysql:dbname={$database};host={$host}";
self::$dbh = new PDO($dsn, $user, $pass);
self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
# 2. always use an interface which defines required logic
interface SimpleDatabaseInterface {
public function onRunQuery($query);
}
# 3. create the accessible controller for inherited & ancillary logic
class SimpleDatabaseController extends SimpleDatabaseSocket implements SimpleDatabaseInterface {
private $host = "";
private $base = "";
private $usr = "";
private $pwd = "";
private $table = "";
# when we create the controller, you MUST pass the connection params
public function __construct($host, $usr, $pwd, $base) {
$this->setUsr($usr);
$this->setPwd($pwd);
$this->setBase($base);
$this->setHost($host);
}
# mysql host/ip
public function setHost($host) {
$this->host = $host;
}
# mysql database
public function setBase($base) {
$this->base = $base;
}
# mysql username
public function setUsr($usr) {
$this->usr = $usr;
}
# mysql password
public function setPwd($pwd) {
$this->pwd = $pwd;
}
# allow this controller to switch tables dynamically.
public function onChangeTable($table) {
$this->table = $table;
}
# connect to the database
protected function onConnect() {
$this->connect($this->base, $this->usr, $this->pwd, $this->host);
}
# connects to the DB and runs a custom query
public function onRunQuery($query) {
try {
if (!self::$dbh)
$this->onConnect();
$result = self::$dbh->query($query);
$out = $result->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
}
return $out;
}
}
# exmaple usage
$mysql = new SimpleDatabaseController("HOSTNAME","USERNAME","PASSWORD","DATABASE");
$result = $mysql->onRunQuery("SELECT * FROM TABLE LIMIT 0,2");
print("<pre>" . print_r($result, true) . "</pre>");