PDO类使用链方法


PDO class use chain method

这是我的"wrapper"类,通过PDO(它更大,这是现在重要的部分)

class DB
    {
        protected $pdo;
        protected $dsn;
        protected $username;
        protected $password;
        protected $driverOptions;
        protected $query;
        public function __construct($dsn, $username = '', $password = '', array $driverOptions = [])
        {
            $this->dsn = $dsn;
            $this->username = $username;
            $this->password = $password;
            $this->driver_options = $driverOptions;
        }
        public function connect()
        {
            $this->pdo = new PDO($this->dsn, $this->username, $this->password, (array)$this->driver_options);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $this->pdo;
        }
        public function myQuery($sql)
        {
            $this->query = $this->pdo->prepare($sql);
            $this->query->execute();
            return $this->query;
        }
        public function all()
        {
            $all = $this->query->fetchAll();
            $this->query->closeCursor();
            return $all;
        }
    }

这可以完美地工作(如果有一点改变,特别是通过添加类型提示),如下所示:

$class = new myPDO('mysql:host=localhost;dbname=***', 'login', 'pass');
$prepare = $class->connect()->prepare('SELECT * FROM test');
$prepare->execute();
$result = $prepare->fetch();

但是我想这样使用它:

$pdo = new DB('mysql:host=localhost;dbname=***', 'login', 'pass');
$result = $pdo->connect()->myQuery('SELECT * FROM test')->all();

在我的IDE中有这个错误:

在类PDO中找不到方法'myQuery'

你的类是作为PDO的抽象,但是你泄露了实际的PDO对象每当你写这个:

return $this->pdo;

该类的消费者永远不需要知道这个对象的存在,所以你不应该给他们这个对象。

要获得链接效果,您所要做的就是将调用者已经拥有的对象返回给调用者,准备进行另一次调用。换句话说:

return $this;