ファクトリ パターンのようにデータを取得できる 1 つのデータベース コントローラーが望ましいです。以下の例では、コントローラーを 1 つだけ作成して、コンポーネントが必要に応じて使用できるようにすることができます。
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>");