| Код | <?php
class DB { public function __construct($type, $host, $user, $password, $db) { switch ($type) { case 'mysql': return new MySQL($host, $user, $password, $db); break; } } }
?> |
| Код | <?php
class MySQL { private $host; private $user; private $password; private $db; private $cid; private $persistent = FALSE; private $errors;
public function __construct($host, $user, $password, $db) { $this->host = $host; $this->user = $user; $this->password = $password; $this->db = $db; }
public function connect() { if ($this->cid = ($this->persistent) ? mysql_pconnect($this->host, $this->user, $this->password) : mysql_connect($this->host, $this->user, $this->password)) { if (mysql_select_db($this->db, $this->cid)) { return TRUE; } else { $errors[] = mysql_error($this->cid); return FALSE; } } else { $errors[] = mysql_error($this->cid); return FALSE; } }
public function query($query) { $query = mysql_real_escape_string($query); if ($result = mysql_query($query, $this->cid)) { return $result; } else { $errors[] = mysql_error($this->cid); return FALSE; } }
public function disconnect() { if ($this->cid) { mysql_close($this->cid); } }
public function __destruct() { $this->disconnect(); } }
?> |
Проблема в строке return new MySQL($host, $user, $password, $db). Мне нужно сделать, чтобы работать можно было так:
| Код | <?php
$db = new DB('mysql', 'localhost', 'root', '', 'db'); $db->connect(); $db->query('...');
?> |
Но, что-то не очень получается. Подскажите как организовать.
ЗЫ: Подход к написанию класс правильный? Или может стоит подумать о других вариантах реализации? |