php PDO扩展

时间:2014-03-06 15:25:31

标签: php class pdo extending

我不是要创建自己的PDO类,只是扩展它,这样我就可以在自己的执行函数(myexecute)中插入try catch语句,所以我不必每次都编写代码。

首先,这是一个好主意吗?或者我应该废弃它?

所以我想要这个:

$DB = new Database ( HOST, DB, USER, PASS );
$query = $DB->prepare("INSERT * FROM books WHERE title = :title");
$query->bindParam( ':title', $_POST['title'] );
$query->myexecute();

如果出现问题,我的函数(myexecute)会对错误处理进行排序 问题是我得到这个错误:

Fatal error: Call to undefined method PDOStatement::myexecute()

任何想法我做错了什么?

 class Database extends PDO
    {
    private $dbh;
    private $error;
    private $total;
    private $p_query;


    public function __construct($hostname,$dbname,$username,$password)
    {
        try  
        { 
            $dsn = 'mysql:host='.$hostname.';dbname='.$dbname;
            parent::__construct($dsn, $username, $password);
        } 
        catch(PDOException $e)
        {
            echo "DataBase Error: Connection error.<br>".$e->getMessage();
            exit;
        }
    } 

    public function myexecute()
    {
        try 
        {
            return parent::execute();
        } 
        catch (PDOException $e) 
        {
            echo "DataBase Error: The user could not be added.<br>".$e->getMessage();
            exit;
        }   
        catch (Exception $e) 
        {
            echo "General Error: The user could not be added.<br>".$e->getMessage();
            exit;
        }
    }
}

3 个答案:

答案 0 :(得分:0)

要执行您要执行的操作,您必须编写一个围绕PDOStatement的包装器并覆盖Database类中的prepare方法以返回PDOStatement的包装器。这样你就可以在PDOStatement的子类中使用myexecute方法了。

答案 1 :(得分:0)

希望扩展PDOStatement很常见,并且受PDO支持。您只需指定用于语句的类。

class DBIStatement extends \PDOStatement
{
    public function fetchrow_hash()
    {
        $rows = $this->fetchAll();
        return (count($rows) == 1) ? new DBIDataRow($rows[0]) : new DBIDataRow(array());
    }
}
class DBI
{
    public $dbh;

    public function __construct($type, $host, $name, $user, $pass)
    {   
        $dsn = sprintf('%s:host=%s;dbname=%s',$type,$host,$name);
        $this->dbh = new \PDO($dsn,$user,$pass,array(
            \PDO::ATTR_ERRMODE,           PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC,
        ));
        // *** This is what tells PDO to use your statement class.
        $this->dbh->setAttribute(\PDO::ATTR_STATEMENT_CLASS,array('DBIStatement'));
    }

不要被反斜杠吓到。这是命名空间应用程序的一部分。

唯一奇怪的是我无法在pdp构造函数中传递语句类,就像我可以知道其他属性一样。但确实有效。

根本不需要愚弄pdo准备方法。

答案 2 :(得分:0)

您不必使用原始PDO编写try catch语句。

因此,您尝试扩展PDO的原因是错误的。

只是放弃了在每个语句上写try try的坏习惯,你可以使用原始PDO。