문제
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 = ".$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의 확장 키워드를 사용할 수 있습니다.
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!');
내 표준 방법은 a를 만드는 것입니다 하나씩 일어나는 것 데이터베이스 액세서 역할을하는 클래스 및 그러한 액세스가 필요한 모든 것이 상속되는 기본 클래스.
그래서:
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 $_db;
public function __construct(PDO $db) {
$this->_db = $db
}
public function comment() {
return $this->_db->query(/*something*/);
}
}