Is this an acceptable PHP connection class?
I've recently been trying to come up with an easy to use connection class.
The following implementation connects, queries and returns results and a
count.
Am I on the right track? Or does this go against standards completely? I'm
trying to stay away from the requirement to instantiate the class, so I'm
using a static method initially and returning a query object that can
fully chain.
class DB {
protected static $_connection = null;
public static function connect() {
if(!self::$_connection) {
try {
$pdo = new PDO('mysql:host=localhost;dbname=database', 'root',
'');
} catch(PDOException $e) {
die($e->getMessage());
}
self::$_connection = $pdo;
}
}
public static function query($sql) {
self::connect();
return new Query($sql);
}
}
class Query extends DB {
protected $_pdo = null,
$_query = null,
$_results = null,
$_count = null;
public function __construct($sql) {
$this->_pdo = self::$_connection;
$this->_query = $this->_pdo->prepare($sql);
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
return $this;
} else {
die('Query failed');
}
}
public function results() {
return $this->_results;
}
public function count() {
return $this->_count;
}
}
And the usage:
$users = DB::query('SELECT * FROM users LIMIT 10');
if(!$users->count()) {
echo 'Sorry, no results.';
} else {
foreach($users->results() as $user) {
echo $user->username, '<br>';
}
}
No comments:
Post a Comment