Entity 클래스
데이터를 단순 배열이 아닌 객체로 다루며, 커스텀 메서드를 추가합니다.
Entity 클래스 구조
// app/Entities/Post.php
namespace App\Entities;
use CodeIgniter\Entity\Entity;
class Post extends Entity
{
// 타입 자동 캐스팅
protected $casts = [
'id' => 'integer',
'views' => 'integer',
];
// 커스텀 메서드 - 본문 요약
public function getExcerpt(int $length = 100): string
{
return mb_strlen($this->content) > $length
? mb_substr($this->content, 0, $length) . '...'
: $this->content;
}
// 커스텀 메서드 - 날짜 포맷
public function getFormattedDate(): string
{
return $this->created_at?->format('Y-m-d H:i') ?? '';
}
}
실제 Entity 객체 활용 결과
컨트롤러
$post = (new PostModel())->first(); // Post 엔티티 반환
$post->id (integer 캐스팅)
1 (integer)
$post->title
CodeIgniter 4 시작하기
$post->getExcerpt(50)
CodeIgniter 4는 PHP 프레임워크 중 빠르고 가벼운 것으로 유명합니다.
MVC...
$post->getFormattedDate()
2026-05-27 13:21
$post->views (integer 캐스팅)
142 (integer)
$post->author
김철수
Entity vs 배열: Entity는 타입 캐스팅, 커스텀 getter/setter, 비즈니스 로직을 담을 수 있습니다.
Model에서
protected $returnType = Post::class로 설정하면 자동으로 Entity를 반환합니다.