在PHP中,如何设置默认的PDO Fetch Class?

McH*_*bie 6 php pdo

使用PDO ::的setAttribute,怎么设置我什么时候提供的类名PDO::ATTR_DEFAULT_FETCH_MODEPDO::FETCH_CLASS.

这是我正在使用的代码..我想设置它所以我的所有行都作为以下实例返回DB_Row:

class DB_Row extends ArrayObject {}

$db = new PDO('mysql:dbname=example;host=localhost', 'user', 'pass');
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS);

$stmt = $db->query("SELECT * FROM `table` WHERE `id` = 1;");

$row = $stmt->fetch(); // I want a DB_Row by default!
Run Code Online (Sandbox Code Playgroud)

上面的代码导致了一个,PDOException因为没有分配DB_Row类名.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General    error: No fetch class specified
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

提前致谢..

解决方案:我使用了fireeyedboy的回答.它对我的情况起了最好的作用,因为我已经将PDOStatement扩展用于记录目的......

class DB extends PDO {
    public function __construct($host = null, $user = null, $pass = null, $db = null) {
        try {
            parent::__construct('mysql:dbname=' . $name .';host=' . $host, $user, $pass);
            $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS);
            $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DB_Query', array('DB_Row')));
        } catch (PDOException $e) {
            die('Database Error');
        }
    }
}

class DB_Query extends PDOStatement {
    private $class;
    protected function __construct ($class = 'DB_Row') {
        $this->class = $class;
        $this->setFetchMode(PDO::FETCH_CLASS, $this->class);
    }
}

class DB_Row extends ArrayObject {
    public function __set($name, $val) {
        $this[$name] = $val;
    }
    public function __get($name) {
        return $this[$name];
    }
}
Run Code Online (Sandbox Code Playgroud)

joh*_*nes 5

我认为它应该返回一个stdclass实例,所以这将是一个错误 - 但必须在代码中查找以验证.如果到那时没有接受的答案,我们会这样做.

什么工作是使用PDO :: FETCH_CLASS | PDO :: FETCH_CLASSTYPE然后提供类名作为第一列.虽然这是一个黑客:

$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);

$stmt = $db->query("SELECT 'classname', * FROM `table` WHERE `id` = 1;");
Run Code Online (Sandbox Code Playgroud)

编辑:正如这里承诺的代码.相关代码在这里http://lxr.php.net/xref/PHP_5_4/ext/pdo/pdo_stmt.c#940因此,只有使用FETCH_CLASSTYPE才能设置for fetch().另一种方法是使用PDOStatement :: fetchObject()


Dec*_*ler 4

另一种黑客方法是扩展PDOStatement、重写其 fetch 方法并让您的PDO实例使用它作为默认语句类。

作为一个例子,我将演示覆盖fetch()1并离开fetchAll(),如果你想走这条路,你该怎么办:

class Db_Row
{
}

class PDOStatementWithClass
    extends PDOStatement
{
    private $fetch_class;

    // PHP complained when I tried to make this public
    protected function __construct( $fetch_class = 'StdClass' )
    {
        // internally set the fetch class for later use
        $this->fetch_class = $fetch_class;
    }

    // let $fetch_style default to PDO::FETCH_CLASS in stead of PDO::FETCH_BOTH
    public function fetch( $fetch_style = PDO::FETCH_CLASS, $cursor_orientation = PDO::FETCH_ORI_NEXT, $cursor_offset = 0 )
    {
        // make sure we're really dealing with the correct fetch style
        if( $fetch_style == PDO::FETCH_CLASS )
        {
            // then automatically set the fetch mode of this statement
            parent::setFetchMode( $fetch_style, $this->fetch_class );
        }

        // go ahead and fetch, we should be good now
        return parent::fetch( $fetch_style, $cursor_orientation, $cursor_offset );
    }
}

$db = new PDO( /* etc... */ );
// set default fetch mode to FETCH_CLASS
$db->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS );
// override what statement class to use, and provide constructor arguments (found out by trial and error)
$db->setAttribute( PDO::ATTR_STATEMENT_CLASS, array( 'PDOStatementWithClass', array( 'Db_Row' ) ) );
Run Code Online (Sandbox Code Playgroud)

这样做的另一个好处是,您只需PDO::FETCH_CLASS在应用程序中定义一次,而不是在每个查询中定义一次。


1)我很惊讶 PHP 没有抱怨重写方法的签名。