Should database queries to populate object properties be done in the constructor or in a separate method in PHP OOP?

In PHP OOP, it is generally recommended to separate the database queries to populate object properties from the constructor in order to keep the constructor clean and focused on object initialization. This separation helps improve code readability, maintainability, and testability. By creating a separate method for querying the database, you can easily reuse the code and make modifications without affecting the constructor.

class User {
    private $id;
    private $name;

    public function __construct($id) {
        $this->id = $id;
        $this->fetchUserData();
    }

    private function fetchUserData() {
        // Database query to fetch user data based on $this->id
        // Assign fetched data to object properties
        $this->name = "John Doe"; // Example data
    }
}