Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I intercept PDO calls?

I'm trying to implement a plugin API in a PHP-based product I'm working on. I created a class that inherits from PHP's PDO class and then added some extra methods. Trouble is, I want to intercept things like PDO's .query(), .exec(), .execute(), and .fetchAll() in the plugin API, handling the arguments passed to/from those methods. I tried using the __call($method,$args) interceptor technique, but it won't work in this case because I have no way to mark the PDO methods as protected.

How do I make a class that inherits from PDO, and then intercept PDO class methods before they are sent off to the parent class? The goal is to intercept arguments passed to/from those methods so that my plugin API will work. This is the missing piece I don't have in my plugin API for the product I'm working on.

like image 395
Volomike Avatar asked Mar 23 '26 23:03

Volomike


1 Answers

Instead of inheriting the PDO, just wrap it.

Just an example:

class MyDB {
    private $dbh;

    public function __construct($dsn, $username, $password, $driver_options = array()) {
       $this->dbh = new PDO($dsn, $username, $password, $driver_options);
    }

    public function query($statement) {
        //do something you want
        //...
        return $this->dbh->query($statement);
    }

    //and so on....
}
like image 133
xdazz Avatar answered Mar 26 '26 13:03

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!