How can the Active Record Pattern be implemented in PHP for efficient data handling?
The Active Record Pattern is a design pattern that maps database records to objects in an object-oriented programming language like PHP. This pattern helps in efficient data handling by encapsulating database operations within the object itself, making it easier to work with data in an object-oriented way.
class User extends ActiveRecord {
protected $table = 'users';
public $id;
public $name;
public $email;
public function save() {
if ($this->id) {
// Update the existing record
$query = "UPDATE $this->table SET name = '$this->name', email = '$this->email' WHERE id = $this->id";
// Execute the query
} else {
// Insert a new record
$query = "INSERT INTO $this->table (name, email) VALUES ('$this->name', '$this->email')";
// Execute the query
}
}
public function delete() {
$query = "DELETE FROM $this->table WHERE id = $this->id";
// Execute the query
}
}
$user = new User();
$user->name = 'John Doe';
$user->email = 'john.doe@example.com';
$user->save();
$user2 = new User();
$user2->id = 1;
$user2->name = 'Jane Doe';
$user2->email = 'jane.doe@example.com';
$user2->save();
$user3 = new User();
$user3->id = 2;
$user3->delete();