By default models return arrays. An Entity is a class that represents one row as an object, so you can add useful methods and automatic conversions.
Create an entity
php spark make:entity Post creates app/Entities/Post.php extending CodeIgniter\Entity\Entity.
Use it in the model
Set protected $returnType = \App\Entities\Post::class;. Now find() and findAll() return Post objects, and you read columns as properties: $post->title.
Setters and getters
- A method
setTitle($value)runs when you assign$post->title = ...— great for cleaning data or creating a slug - A method
getTitle()runs when you read$post->title - Add your own methods, such as
isPublished()orexcerpt()
Casts
protected $casts = ['is_featured' => 'boolean', 'options' => 'json-array']; converts values automatically. created_at and updated_at are turned into Time objects by default, so $post->created_at->humanize() gives "2 hours ago".
Saving
Pass the entity to $model->save($post). Only changed fields are updated.
Example
<?php
namespace App\Entities;
use CodeIgniter\Entity\Entity;
class Post extends Entity
{
protected $casts = ['is_featured' => 'boolean'];
public function setTitle(string $title)
{
$this->attributes['title'] = $title;
$this->attributes['slug'] = url_title($title, '-', true);
return $this;
}
public function excerpt(int $words = 20): string
{
helper('text');
return word_limiter(strip_tags($this->attributes['body'] ?? ''), $words);
}
}
// Usage (PostModel has $returnType = \App\Entities\Post::class)
$post = new \App\Entities\Post();
$post->title = 'My First Entity Post';
$post->body = 'Entities make data easy to work with.';
model('PostModel')->save($post);
echo $post->slug; // my-first-entity-post
Assigning the title also creates the slug "my-first-entity-post". excerpt() can be called in views as $post->excerpt().