質問
MySQLiクラスを拡張してそのすべてのSQLクエリを実行するクラスを作成できるようにしたい。
$mysql = new mysqli('localhost', 'root', 'password', 'database') or die('error connecting to the database');
他のメソッドやクラスで使用する$ mysqlオブジェクトをグローバル化せずにこれを行う方法がわかりません。
class Blog {
public function comment() {
global $mysql;
//rest here
}
}
ご協力いただければ幸いです。
ありがとう。
解決
シングルトンDataAccessクラスを作成し、そのクラスをグローバル構成ファイルにインスタンス化し、 $ query = DataAccess :: query(" SELECT * FROM blog WHERE id =&quotのようにBlogクラスで呼び出すことをお勧めします;。$ id)
。
シングルトンパターンを見ると、デザインパターンを理解するのは非常に簡単です。この状況に最適です。
DataAccessクラスには、 query
、 fetchAssoc
、 numRows
、 checkUniqueValue
、などのいくつかのメソッドを含めることができますtransactionStart
、 transactionCommit
、 transactionRollback
など。これらの機能は、DataAccessクラスによって実装されるインターフェイスとして設定することもできます。これにより、DataAccessクラスを複数のデータベース管理システムに簡単に拡張できます。
上記は私のDataAccessモデルについてほとんど説明しています。
他のヒント
似たようなことに取り組んでいた。データベースログインをカプセル化するこのシングルトンクラスに満足しています。
<?php
class db extends mysqli
{
protected static $instance;
protected static $options = array();
private function __construct() {
$o = self::$options;
// turn of error reporting
mysqli_report(MYSQLI_REPORT_OFF);
// connect to database
@parent::__construct(isset($o['host']) ? $o['host'] : 'localhost',
isset($o['user']) ? $o['user'] : 'root',
isset($o['pass']) ? $o['pass'] : '',
isset($o['dbname']) ? $o['dbname'] : 'world',
isset($o['port']) ? $o['port'] : 3306,
isset($o['sock']) ? $o['sock'] : false );
// check if a connection established
if( mysqli_connect_errno() ) {
throw new exception(mysqli_connect_error(), mysqli_connect_errno());
}
}
public static function getInstance() {
if( !self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
public static function setOptions( array $opt ) {
self::$options = array_merge(self::$options, $opt);
}
public function query($query) {
if( !$this->real_query($query) ) {
throw new exception( $this->error, $this->errno );
}
$result = new mysqli_result($this);
return $result;
}
public function prepare($query) {
$stmt = new mysqli_stmt($this, $query);
return $stmt;
}
}
使用するには、次のようなものがあります:
<?php
require "db.class.php";
$sql = db::getInstance();
$result = $sql->query("select * from city");
/* Fetch the results of the query */
while( $row = $result->fetch_assoc() ){
printf("%s (%s)\n", $row['Name'], $row['Population']);
}
?>
PHPのextendsキーワードは、他のクラスにのみ使用できます。
class MyCustomSql extends mysqli {
public function __construct($host, $user, $password, $database) {
parent::__construct($host, $user, $password, $database);
}
public function someOtherMethod() {
}
}
$sql = new MyCustomSql('localhost', 'root', 'password', 'database') or die('Cannot connect!');
または継承の代わりにオブジェクト集約を使用する方が良い:
class MySqlManipulator {
private $db;
public function __construct($host, $user, $password, $database) {
$this->db = new mysqli($host, $user, $password, $database);
}
public function someOtherMethod() {
return $this->db->query("SELECT * FROM blah_blah");
}
}
$mysqlmanipulator = new MySqlManipulator('localhost', 'root', 'password', 'database') or die('Cannot connect!');
私の標準的な方法は、データベースアクセサーとして機能するシングルトンクラスを作成することです。そのようなアクセスを必要とするすべてのものが継承する基本クラス。
だから:
class Base {
protected $db;
function __construct(){
$this->db= MyDBSingleton::get_link();
//any other "global" vars you might want
}
}
class myClass extends Base {
function __construct($var) {
parent::__construct();// runs Base constructor
$this->init($var);
}
function init($id) {
$id=(int) $id;
$this->db->query("SELECT * FROM mytable WHERE id=$id");
//etc.
}
}
例外をスローする PDO をご覧くださいクエリが失敗した場合にキャッチします。広く使用されテストされているため、使用中に既存のソリューションを見つけるのに問題はないはずです。
ブログクラスに挿入するには:
class Blog {
private 例外をスローする PDO をご覧くださいクエリが失敗した場合にキャッチします。広く使用されテストされているため、使用中に既存のソリューションを見つけるのに問題はないはずです。
ブログクラスに挿入するには:
<*>db;
public function __construct(PDO $db) {
$this->_db = $db
}
public function comment() {
return $this->_db->query(/*something*/);
}
}