PDO类使用链式方法

时间:2015-05-28 19:22:29

标签: php class oop methods pdo

这是我的“包装”类,比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'

1 个答案:

答案 0 :(得分:2)

你的类充当了对PDO的抽象,但只要你写这个就泄漏了实际的PDO对象:

return $this->pdo;

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

要获得链接效果,您所要做的就是让调用者返回他们已有的对象,准备再拨打电话。换句话说:

return $this;