Master object-oriented programming, design patterns, security, and high-performance PHP applications.
<?php
// Advanced OOP Example with Traits, Interfaces, and Abstract Classes
interface Repository {
public function find($id);
public function save($entity);
}
interface Cacheable {
public function getCacheKey(): string;
public function getCacheTTL(): int;
}
abstract class BaseRepository {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
protected function beginTransaction() {
$this->db->beginTransaction();
}
protected function commit() {
$this->db->commit();
}
protected function rollback() {
$this->db->rollBack();
}
}
trait Timestampable {
protected $createdAt;
protected $updatedAt;
public function setTimestamps(): void {
$this->createdAt = new DateTime();
$this->updatedAt = new DateTime();
}
}
class User extends BaseRepository implements Cacheable {
use Timestampable;
private $id;
private $name;
private $email;
public function __construct(array $data = []) {
$this->hydrate($data);
$this->setTimestamps();
}
private function hydrate(array $data): void {
foreach ($data as $key => $value) {
if (property_exists($this, $key)) {
$this->$key = $value;
}
}
}
public function getCacheKey(): string {
return 'user.' . $this->id;
}
public function getCacheTTL(): int {
return 3600;
}
public function find($id) {
// Implementation
}
public function save($entity) {
// Implementation
}
}
?>
Test your advanced PHP knowledge!