扩展PDO类 [英] Extend PDO class

查看:76
本文介绍了扩展PDO类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想开始使用PDO(从MySQL扩展切换),我想添加一些方法,但仍然具有完整的PDO功能.我想实现这样的功能:

I want to start using PDO (switching from MySQL extension) and I would like to add some methods but to still have the entire PDO functionality. I would like to implement a function like this:

$db->getAll("SELECT * FROM table WHERE field1=:foo AND field2=:baz", array('foo'=>$foo, 'baz'=>$baz));

我认为最好的方法是扩展PDO类,但是在这种情况下,我将没有该类的实例能够在该类中使用它.有什么主意吗?

I think the best way is to extend the PDO class but in this case I would not have the instance of the class to be able to use it inside the class. Any idea?

推荐答案

我建议不要扩展PDO,而应该像其他ORM那样围绕它创建一个库/包装器.

I would advise against extending PDO, but rather creating a library/wrapper around it which other ORM's do.

我将您的示例代码构建为一个简单的类进行解释.

I will construct your example code into a simple class for explanation.

class MyDB
{

    private $pdo;

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

    public function getAll($query, array $params)
    {
        $statement = $this->pdo->prepare($query);
        $statement->execute($params);
        return $statement->fetchAll();
    }

    public function getPdo()
    {
        return $this->pdo;
    }

    /**
     * This is called if the method cannot be found.
     * Pass it to PDO to handle.
     *
     * @param $name
     * @param $arguments
     */
    public function __call($name, $arguments)
    {
        return call_user_func(array($this->pdo, $name), $arguments)
    }

}

如果您真的想直接访问PDO,那么我提供了一种魔术方法,但我不建议您采用这种方法.参见 http://www.php.net/manual/zh-CN/language .oop5.magic.php

If you really want to access PDO directly then I've included a magic method but I don't recommend you take that route. See http://www.php.net/manual/en/language.oop5.magic.php

做这种事情对于学习很有趣,但是如果您想要认真的ORM,那么请看一下这样的问题

Doing this sort of stuff is fun for learning, but if you want a serious ORM then take a look at this SO question Good PHP ORM Library? and also research yourself.

这篇关于扩展PDO类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆