What is BaseEntity casting in CodeIgniter 4?
Why Interviewers Ask This
This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.
Answer
CI4's Entity casting system automatically converts data types when getting or setting Entity properties. Built-in cast types: integer, float, string, boolean, json (encodes/decodes JSON automatically), array, csv (comma-separated values), datetime (returns a Time object), timestamp, uri. Define casts: protected $casts = ["is_admin" => "boolean", "metadata" => "json", "tags" => "csv", "created_at" => "datetime"]. Custom cast types: implement CastInterface and register in the model. Nullable casts: "age" => "?integer". Casting in entities greatly reduces data transformation boilerplate — setting $entity->tags = ["php", "ci4"] automatically serializes to CSV, and getting $entity->tags returns an array. This brings CI4 models closer to Eloquent's casting functionality.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your CodeIgniter experience.