Entities
An entity is a class whose object represents one row of a table. The model still finds and saves records, but returns them as objects instead of arrays. Such a class is a good home for everything that belongs to one record: type casting, formatting, small calculations. Entities live in the app/Entities folder.
Creating an entity
php spark make:entity PostThe command creates the file app/Entities/Post.php. The skeleton is already enough to work with:
// app/Entities/Post.php
namespace App\Entities;
use CodeIgniter\Entity\Entity;
class Post extends Entity
{
}There is no need to list the table columns in the class: they become properties of the object automatically.
Connecting it to the model
To make the model return objects, put the entity class into the $returnType property:
// app/Models/PostModel.php
protected $returnType = \App\Entities\Post::class;Now find() and findAll() return Post objects, and a view uses $post->title instead of $post['title']:
<!-- app/Views/posts/show.php -->
<h1><?= esc($post->title) ?></h1>
<p><?= esc($post->body) ?></p>The /posts/1 page looks as before; only the way of accessing fields has changed.
Type casting
All values come from the database as strings. The $casts property turns them into the right type, and $dates into date objects:
// app/Entities/Post.php
class Post extends Entity
{
protected $casts = [
'id' => 'integer',
'status' => 'integer',
];
protected $dates = ['created_at', 'updated_at'];
}After that $post->status === 1 gives true, and a date can be formatted right in the view: <?= $post->created_at->format('d.m.Y') ?>.
Your own methods
A method named get plus a property name is called when that property is read:
public function getExcerpt(): string
{
return mb_substr($this->attributes['body'], 0, 100) . '…';
}
public function isPublished(): bool
{
return $this->status === 1;
}In a view <?= esc($post->excerpt) ?> prints the first hundred characters of the text, although the table has no excerpt column. The $this->attributes array holds the original values of the row.
Creating and saving
An entity is filled with data and passed to the model:
$post = new \App\Entities\Post();
$post->fill([
'title' => 'New post',
'body' => 'The text of the post',
]);
model(PostModel::class)->save($post);The save() method adds a row to the table. If the object came from the database and was changed, the same call saves only the changed fields.
Array or entity
| Option | When it fits |
|---|---|
'array' | Simple pages, data is output as is |
| An entity class | The record has logic of its own: statuses, formatting, computed fields |
Entities are optional. In the following lessons of the course records stay arrays to keep the examples shorter.
Common mistake
After $returnType is changed, old views with $post['title'] stop working: an entity object is not an array, and PHP reports an error. Change the access style in all views of the model at once. If an array is what you need, $post->toArray() returns it.