我更喜欢一个数据库控制器,您可以从工厂模式中获取数据。在下面的示例中,您可以只创建一个控制器并让您的组件根据需要使用它。
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>");