// New way: direct enum $status = $stmt->fetch(PDO::FETCH_ENUM); // UserStatus::Active
class UserDTO { public function __construct( public int $id, public string $name ) {} } $stmt = $pdo->prepare("SELECT id, name FROM users"); $stmt->execute(); $stmt->setFetchMode(PDO::FETCH_INTO, new UserDTO(0, '')); while ($obj = $stmt->fetch()) { echo $obj->name; // Fully populated DTO }
// Old way: string $statusString = $stmt->fetchColumn(); // 'active'
$pdo = new class($dsn, $user, $pass) extends PDO { private ?PDO $connection = null; private function connect(): void { if (!$this->connection) { $this->connection = new PDO($this->dsn, ...); } }
While not built into core PDO, the community pattern using ProxyManager or LazyConnection has become standard:
if ($stmt->getAttribute(PDO::ATTR_DRIVER_NAME) === 'mysql') { $stmt->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); } No more guessing which driver you're on. 4.1 Lazy Connections (PHP 8.1) Using PDO::ATTR_EMULATE_PREPARES wisely is old news. The real v20 feature is implicit lazy connection via proxies:
Pdo V20 — Extended Features
// New way: direct enum $status = $stmt->fetch(PDO::FETCH_ENUM); // UserStatus::Active
class UserDTO { public function __construct( public int $id, public string $name ) {} } $stmt = $pdo->prepare("SELECT id, name FROM users"); $stmt->execute(); $stmt->setFetchMode(PDO::FETCH_INTO, new UserDTO(0, '')); while ($obj = $stmt->fetch()) { echo $obj->name; // Fully populated DTO } pdo v20 extended features
// Old way: string $statusString = $stmt->fetchColumn(); // 'active' name FROM users")
$pdo = new class($dsn, $user, $pass) extends PDO { private ?PDO $connection = null; private function connect(): void { if (!$this->connection) { $this->connection = new PDO($this->dsn, ...); } } while ($obj = $stmt->
While not built into core PDO, the community pattern using ProxyManager or LazyConnection has become standard:
if ($stmt->getAttribute(PDO::ATTR_DRIVER_NAME) === 'mysql') { $stmt->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); } No more guessing which driver you're on. 4.1 Lazy Connections (PHP 8.1) Using PDO::ATTR_EMULATE_PREPARES wisely is old news. The real v20 feature is implicit lazy connection via proxies: