What is CI4 model observer pattern?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized CodeIgniter deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
CodeIgniter 4 models support event callbacks that function like the observer pattern. Unlike Eloquent's dedicated Observer class, CI4 uses model callbacks defined directly in the model. While CI4 does not have a formal Observer class, you can implement the pattern by: creating a listener class and calling it from model callbacks. In the model's callback method: protected function afterInsert(array $data): array { (new UserObserver())->created($data["id"]); return $data; }. For a true observer pattern, create a custom Observer base class that registers callbacks: class UserModel extends Model { public function __construct() { parent::__construct(); $this->afterInsert[] = [UserObserver::class, "created"]; } }. Alternatively, use CI4's Events system: fire custom events from model callbacks and register listeners in app/Config/Events.php — this provides true decoupling between models and their observers.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex CodeIgniter answers easy to follow.