3

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
Volomike
  • 23,743
  • 21
  • 113
  • 209

1 Answers1

4

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....
}
Volomike
  • 23,743
  • 21
  • 113
  • 209
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • This is what I ended up doing. I also had to do fancy stuff because PDO creates a statement object with class methods against that. So, I had to create a PDOStatementStub class that does something like the above as well. I then used __call() to intercept and run this through the private handle variable's class methods. – Volomike Feb 08 '12 at 10:51