How can object-oriented principles be better applied in PHP code for database interactions, especially when dealing with entity objects and repositories?

When dealing with entity objects and repositories in PHP for database interactions, it is important to adhere to object-oriented principles such as encapsulation, inheritance, and polymorphism. One way to do this is by creating separate classes for each entity object that represent a table in the database, and separate classes for repositories that handle interactions with the database for each entity. This separation of concerns helps in maintaining a clean and organized codebase.

// Entity class representing a user
class User {
    private $id;
    private $username;
    private $email;

    // Constructor, getters, and setters
}

// Repository class for User entity
class UserRepository {
    private $db;

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

    public function findById($id) {
        // Database query to fetch user by ID
    }

    public function findByUsername($username) {
        // Database query to fetch user by username
    }

    public function save(User $user) {
        // Database query to save user
    }

    public function delete(User $user) {
        // Database query to delete user
    }
}