• 0

[php] Overriding PDO


Question

I am writing some code using PDO as my database connection handler, and I do like the functionality it offers. However, I want to write a layer between my code and PDO that does some logging, etc.

I need to override PDOstatement as called by PDO->prepare...

I have searched but cannot find the full code for PDO or PDOstatement anywhere...

Can anyone help?

My end goal is to override the execute function, logging what is attempting to execute, then returning the original function.

Thanks

Link to comment
https://www.neowin.net/forum/topic/856004-php-overriding-pdo/
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Better late than never, here you go.

Comments on the PHP Manual seem to indicate that extending PDO/PDOStatement like this has a side effect that causes PDO to not close the connection until the end of the script. This may or may not be an issue depending on whether or not you need to close and reopen connections in the same script.

<?php

class database extends PDO 
{
	protected $query;

	public function __construct($dsn, $username = '', $password = '', $driver_options = array()) 
	{
		parent::__construct($dsn, $username, $password, $driver_options);
		$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('db_statement', array($this)));
	}

	public function prepare($statement, $driver_options = array())
	{
		$this->query = $statement;
		return parent::prepare($statement, $driver_options = array());
	}

	public function last_query()
	{
		return $this->query;
	}
}

class db_statement extends PDOStatement 
{
	protected $pdo;

	protected function __construct($pdo)
	{
		$this->pdo = $pdo;
	}

	public function execute($args = null)
	{
		// Perform logging here. PDO object is accessible
		// from $this->pdo.

		echo $this->pdo->last_query();

		if (!is_array($args)) {
			$args = func_get_args();
		}

		return parent::execute($args);
	}
}

$database = new database('mysql:host=localhost;dbname=database', 'username', 'password');

$statement = $database->prepare('SELECT column FROM table WHERE column = ?');

$statement->execute(array(100));

?>

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.