I somewhat recently asked a question on here for advice on a PDO function that I had written. I got some good advice from a user, and went with it. I had used that function for about 3 months which is also about how long I have been using PDO in general, until someone mentioned to me that they would have made it a class.
I have never worked with classes before in PHP, and I wanted to give it a shot. So I did.
Now, since this is my first class, I wanted to get some advice on it and some constructive criticism. I want my code to keep on improving, and I want to know the best way to do some things. I don't know if my class is written well, and knowing how I can improve it will definitely help me out.
I've hosted the project on my GitHub. The project is being developed there, and everyone is welcome to contribute to it.
class GrumpyPdo {
private $host, $user, $pass, $db, $charset;
private $dsn, $databaseObject;
private $killOnError = true;
private $echoOnError = false;
//these options can obviously be changed but not "on the fly" (yet).
private $opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
function __construct($host, $user, $pass, $db, $charset = "utf8") {
$this->setData([
"host" => $host,
"user" => $user,
"pass" => $pass,
"db" => $db,
"charset" => $charset,
]);
$this->createDBObject();
}
function query($query, $values = []) {
if(!empty($values)) {
$stmt = $this->databaseObject->prepare($query);
$stmt->execute($values);
} else {
$stmt = $this->databaseObject->query($query);
}
return $stmt;
}
function setData($data) {
if(!is_array($data)) {
$this->handleError("GrumpyPDO: Error Code SD13; The setData method requires an array with \$key => \$value pairs.");
}
foreach($data as $k => $v) {
$this->{$k} = $v;
}
return true;
}
function createDBObject() {
$this->dsn = "mysql:host={$this->host};dbname={$this->db};charset={$this->charset}";
$this->databaseObject = new PDO($this->dsn, $this->user, $this->pass, $this->opt);
}
function handleError($error) {
error_log($error);
if($this->echoOnError) echo $error;
if($this->killOnError) die($error);
}
}
query
method. should beif(!empty($values))
note the !.. \$\endgroup\$