Entity 심화
Entity의 $casts, $datamap, Virtual Property, Setter를 라이브로 확인합니다.
Entity 입력 폼
입력값은 setter에서 정규화되고, 접근 시 $casts에 따라 타입 변환됩니다.
$casts 적용 결과
| 속성 | 입력값 (raw) | 캐스팅 후 값 | PHP 타입 |
|---|
Virtual Properties (getter)
$datamap 별칭 접근
1
Entity 클래스 정의
namespace App\Entities;
use CodeIgniter\Entity\Entity;
class UserEntity extends Entity
{
// 외부 키 ↔ 내부 속성 매핑 (alias)
protected $datamap = [
'email_address' => 'email',
];
// Time 객체로 자동 변환
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
// 자동 캐스팅 규칙
protected $casts = [
'id' => 'integer',
'is_active' => 'boolean',
'metadata' => 'json-array', // JSON 자동 직렬화/역직렬화
'tags' => 'csv', // CSV → array 자동 변환
'score' => 'float',
];
// Virtual property (DB 컬럼 없이 getter로만 존재)
public function getFullName(): string
{
return trim($this->attributes['first_name'] . ' ' . $this->attributes['last_name']);
}
// Setter (입력 정규화)
public function setEmail(string $email): static
{
$this->attributes['email'] = strtolower(trim($email));
return $this;
}
}
2
Model에 연결
namespace App\Models;
use App\Entities\UserEntity;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $returnType = UserEntity::class; // ← 핵심
// find/findAll 결과가 UserEntity로 반환됨
}
3
사용 패턴
$user = new UserEntity([
'first_name' => 'john',
'last_name' => 'doe',
'email' => 'JOHN.DOE@Example.COM',
]);
// Setter 자동 호출
echo $user->email; // → 'john.doe@example.com'
echo $user->first_name; // → 'John'
// Virtual property (getter)
echo $user->full_name; // → 'John Doe' (getFullName 호출)
// Datamap alias
echo $user->email_address; // → 'john.doe@example.com'
// toArray / toRawArray
$user->toArray(); // 캐스팅 적용된 배열
$user->toRawArray(); // 원본 속성 (DB 저장용)
$casts 지원 타입
| 타입 | PHP 변환 | 예시 입력 | 변환 결과 |
|---|---|---|---|
integer | (int) | '42' | 42 |
float | (float) | '3.14' | 3.14 |
double | (float) 별칭 | '2.71' | 2.71 |
string | (string) | 42 | '42' |
boolean | (bool) | 0 / 1 / 'true' | false / true |
array | serialize/unserialize | ['a','b'] | array |
csv | CSV ↔ array | 'php,ci4,sql' | ['php','ci4','sql'] |
json | JSON ↔ stdClass | '{"a":1}' | stdClass |
json-array | JSON ↔ array | '{"a":1}' | ['a'=>1] |
datetime | → Time 객체 | '2026-05-26' | CodeIgniter\I18n\Time |
timestamp | → int(unix ts) | '2026-05-26' | 1779562800 |
uri | → URI 객체 | 'https://...' | CodeIgniter\HTTP\URI |
Nullable 타입: 각 타입 뒤에
?를 붙이면 NULL 허용 — 예: 'integer?', 'boolean?'.