What is CodeIgniter's Factories class?

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

The Factories class in CI4 is a lightweight factory pattern that creates and caches instances of framework components. It is used for Models, Libraries, and other components. Access models: $model = model("UserModel") or Factories::models("UserModel") — both return a shared (cached) instance. The Factories class searches across all registered namespaces for the class, enabling module override patterns where an app-level model replaces a module-level one. Factories::models("UserModel", ["getShared" => false]) creates a fresh instance. The factory supports: Factories::components(), Factories::config(). Use Factories::injectMock("models", "UserModel", $mockModel) in tests to inject mock objects. Compared to Laravel's container, Factories is simpler and less powerful but has lower overhead for CI4's design philosophy.

Pro Tip

This topic has CodeIgniter-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.