📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials CodeIgniter 4 Entities in CI4

Entities in CI4

5 min read
Return typed Entity objects from CI4 models with automatic casts and getter/setter methods.

Entities

// Entities are rich model objects (vs plain arrays)
namespace AppEntities;
use CodeIgniterEntityEntity;

class User extends Entity {
    protected $casts = [
        "is_admin"   => "boolean",
        "permissions"=> "json",
        "metadata"   => "array",
    ];

    // Virtual property
    public function getFullName(): string {
        return $this->first_name . " " . $this->last_name;
    }

    // Mutator — auto-hashes password on set
    public function setPassword(string $pass): void {
        $this->attributes["password"] = password_hash($pass, PASSWORD_DEFAULT);
    }
}

// model returns Entity objects when:
protected $returnType = "AppEntitiesUser";

$user = model(UserModel::class)->find(1);
echo $user->full_name;    // calls getFullName()
$user->password = "secret";  // calls setPassword()