How can PHP developers effectively handle data retrieval and object instantiation when working with PDO and Active-Record patterns?

When working with PDO and Active-Record patterns in PHP, developers can effectively handle data retrieval and object instantiation by creating a base model class that encapsulates common database operations. This class can have methods for querying the database using PDO and instantiating objects based on the retrieved data. By using this base model class, developers can abstract away the database interactions and focus on working with objects in their application.

<?php

class BaseModel {
    protected $pdo;

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

    public function findById($table, $id) {
        $stmt = $this->pdo->prepare("SELECT * FROM $table WHERE id = :id");
        $stmt->execute(['id' => $id]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($data) {
            return new $table($data);
        }

        return null;
    }
}

// Example usage
$pdo = new PDO("mysql:host=localhost;dbname=test", "username", "password");
$model = new BaseModel($pdo);
$user = $model->findById('User', 1);

?>