How can PHP developers separate persistence logic from application logic when working with objects and databases?

To separate persistence logic from application logic when working with objects and databases in PHP, developers can utilize the Repository pattern. This pattern involves creating separate classes (repositories) responsible for handling database operations, such as fetching, storing, and deleting data, while keeping the business logic in the domain objects. By doing so, developers can achieve better separation of concerns and improve the maintainability and testability of their code.

// Example of Repository pattern implementation in PHP

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 save(User $user) {
        // Database query to save user data
    }

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

class User {
    private $id;
    private $name;
    
    public function __construct($id, $name) {
        $this->id = $id;
        $this->name = $name;
    }

    // Getter and setter methods
}

// Implementation
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$userRepository = new UserRepository($db);

$user = $userRepository->findById(1);
$user->setName('John Doe');
$userRepository->save($user);