Abstract Classes
Abstract classes can contain both abstract methods (no body) and concrete methods (with implementation). Use them when some behavior is shared but other behavior must be customized.
Abstract classes can contain both abstract methods (no body) and concrete methods (with implementation). Use them when some behavior is shared but other behavior must be customized.
<?php
abstract class BaseRepository {
// Concrete: shared implementation
public function findOrFail(int $id): array {
$result = $this->find($id);
if ($result === null) {
throw new RuntimeException("Record {$id} not found");
}
return $result;
}
// Abstract: subclasses must implement
abstract public function find(int $id): ?array;
abstract public function save(array $data): int;
abstract public function delete(int $id): bool;
}
class UserRepository extends BaseRepository {
public function find(int $id): ?array { /* DB query */ return null; }
public function save(array $data): int { return 1; }
public function delete(int $id): bool { return true; }
}
Abstract classes are great for template method patterns — define the skeleton algorithm in the base class, fill in steps in subclasses.