Models and Entities
Relevant source files
The following files were used as context for generating this wiki page:
In CodeIgniter 4, Models and Entities provide a robust data abstraction layer, forming a key part of the Model-View-Controller (MVC) architectural pattern. Models are responsible for all interactions with a specific database table, offering a simplified interface for common data operations like creating, reading, updating, and deleting (CRUD). They centralize database logic, making applications easier to maintain.
Entities work in tandem with Models, representing a single row of data from a database table as an object. This object-oriented approach allows for the encapsulation of business logic directly related to the data, such as formatting attributes or implementing custom methods. By using Models to return data as Entity objects, developers can work with data in a more intuitive and powerful way.
Sources: source/concepts/mvc.rst, source/models/model.rst, source/models/entities.rst
CodeIgniter Model
The CodeIgniter\Model class provides a set of built-in methods for performing CRUD operations on a database table. It also offers features like data validation, automatic pagination, and event callbacks, which significantly reduce the amount of boilerplate code needed for data management.
Sources: source/models/model.rst:1-15
Core Configuration
To use the model, you create a new class that extends CodeIgniter\Model and configure it by setting a few class properties. These properties define the database table, primary key, allowed fields for mass assignment, and the format of the returned data.
| Property | Type | Description |
|---|---|---|
$table | string | The database table name the model primarily works with. |
$primaryKey | string | The primary key of the table. Defaults to id. |
$returnType | string | The format for results. Can be array, object, or a fully qualified class name (e.g., an Entity). |
$allowedFields | array | An array of field names that can be set during insert or update operations to prevent mass assignment vulnerabilities. |
$useTimestamps | bool | If true, automatically sets created_at and updated_at fields on insert/update. |
$validationRules | array | An array of validation rules to be applied before saving data. |
Sources: source/models/model.rst:110-160
Finding Data
The model provides several methods to retrieve data. The return type is determined by the $returnType property.
find($id): Retrieves a single row by its primary key.findAll(): Returns all rows from the table.first(): Returns the first row from a result set, often used with query builder constraints.where(): A helper that initiates the Query Builder to addWHEREclauses for custom queries.
The following diagram illustrates the flow of retrieving a user record and returning it as an Entity.
This diagram shows a controller calling a model's find() method, which queries the database and populates an Entity object with the result before returning it.
Sources: source/models/model.rst:229-290, source/database/query_builder.rst
Saving Data
The save(), insert(), and update() methods are used to modify data. The save() method is particularly useful as it automatically determines whether to perform an INSERT or an UPDATE based on the presence of the primary key in the data array.
This flowchart shows the internal logic of the save() method, which branches between an UPDATE and an INSERT operation.
Before saving, the model only allows fields specified in the $allowedFields property to be updated, which is a crucial security measure.
Sources: source/models/model.rst:317-360
Validation
Models can automatically validate data before saving it to the database. This is configured by setting the $validationRules and optional $validationMessages properties. If validation fails, the save() method will return false, and errors can be retrieved using $model->errors().
The validation process is triggered within insert(), update(), and save() calls.
This sequence diagram illustrates how a model uses the Validation library during a save() call and returns errors if the data is invalid.
Sources: source/models/model.rst:465-520, source/libraries/validation.rst
Callbacks (Events)
Models have a callback system that allows you to execute custom code at various points in the model's lifecycle. This is useful for tasks like hashing passwords before insertion or processing data after it has been retrieved.
The following table lists the available callbacks:
| Callback | Trigger |
|---|---|
beforeInsert | Before an insert operation. |
afterInsert | After an insert operation. |
beforeUpdate | Before an update operation. |
afterUpdate | After an update operation. |
beforeSave | Before an insert or update operation. |
afterSave | After an insert or update operation. |
beforeDelete | Before a delete operation. |
afterDelete | After a delete operation. |
beforeFind | Before a find* method is executed. |
afterFind | After a find* method has found data. |
Sources: source/models/model.rst:595-620
Entity Class
An Entity class is a simple class that extends CodeIgniter\Entity\Entity and represents a single row from a database table. Its primary purpose is to provide an object-oriented way to work with your data and to house business logic specific to that data.
Sources: source/models/entities.rst:1-10
Core Concepts
Instead of working with arrays or generic objects, Entities allow you to treat your data as a typed object with its own methods and properties. This makes the code cleaner and more expressive.
Key features include:
- Property Access: Access table columns as class properties (e.g.,
$user->email). - Attribute Casting: Automatically transform data when it is set or retrieved.
- Business Logic: Add custom methods to the entity (e.g.,
$user->getFullName()).
Sources: source/models/entities.rst:30-50
Attribute Casting and Mutators
Entities can automatically cast attributes to different data types. For more complex transformations, you can use "mutator" methods.
- Setters (
_set*): A method named_set<PropertyName>($value)will be called automatically when you set a property. This is ideal for tasks like hashing a password when it's assigned. - Getters (
_get*): A method named_get<PropertyName>()is called when you access a property, allowing you to format data on the fly.
The diagram below shows how a setPassword mutator works.
This flowchart illustrates the process of setting a property on an Entity, showing how a mutator method intercepts and transforms the value before it is stored.
Sources: source/models/entities.rst:100-150
Conclusion
CodeIgniter's Model and Entity classes provide a powerful, object-oriented pattern for database interaction. Models abstract away the complexities of database queries and provide hooks for validation and events. Entities represent data as intelligent objects, capable of holding their own business logic. Together, they promote clean, maintainable, and secure code by separating data access logic from data representation, adhering to the principles of the MVC pattern.
Sources: source/models/model.rst, source/models/entities.rst, source/concepts/mvc.rst