
Originally Posted by
ghurtado
Can you share some code with us? I'm curious to see the actual implementation.
Sure. Here is the PDO decorator:
PHP Code:
class LoggedPDO {
function __construct ($db) {
$this->db = $db;
}
function __call ($method, $params) {
return call_user_func_array (array ($this->db, $method), $params);
}
function prepare ($statement) {
$stmt = $this->db->prepare ($statement);
if (is_a ($stmt, 'PDOStatement')):
return new LoggedPDOStatement ($stmt);
else:
throw new Exception ('PDO did not return PDOStatement');
endif;
}
function exec ($query) {
$result = $this->db->exec ($query);
if ($this->db->errorCode() != PDO::ERR_NONE):
$errors = $this->db->errorInfo();
$this->paint ($query, $errors[2]);
endif;
return $result;
}
function paint ($query, $message) {
echo '<pre>';
echo '<table cellpadding="5px">';
echo '<tr><td colspan="2">Message: ' . $message . '</td></tr>';
echo '<tr><td colspan="2">Query: ' . $query . '</td></tr>';
echo '</table>';
echo '</pre>';
}
}
I don't actually have any logging going on yet... as I was coding, I realized it helped me out a lot more to display the query and bound parameters whenever there are errors, along with my failed tests (This is all to support my testing environment, I will implement a logger for a production environment).
Here is the decorator for PDOStatement:
PHP Code:
class LoggedPDOStatement {
function __construct ($stmt) {
$this->stmt = $stmt;
}
function execute ($params = null) {
$result = $this->stmt->execute ($params);
if ($this->stmt->errorCode() != PDO::ERR_NONE):
$errors = $this->stmt->errorInfo();
$this->paint ($errors[2]);
endif;
return $result;
}
function bindValue ($key, $value) {
$this->values[$key] = $value;
return $this->stmt->bindValue ($key, $value);
}
function paint ($message = false) {
echo '<pre>';
echo '<table cellpadding="5px">';
echo '<tr><td colspan="2">Message: ' . $message . '</td></tr>';
echo '<tr><td colspan="2">Query: ' . $this->stmt->queryString . '</td></tr>';
if (count ($this->values) > 0):
foreach ($this->values as $key => $value):
echo '<tr><th align="left" style="background-color: #ccc;">' . $key . '</th><td>' . $value . '</td></tr>';
endforeach;
endif;
echo '</table>';
echo '</pre>';
}
function __call ($method, $params) {
return call_user_func_array (array ($this->stmt, $method), $params);
}
}
Enjoy...
Bookmarks