CodeIgniter

CodeIgniter4のEntityとは?存在意義と実践的な活用法を徹底解説!

この記事は約5分で読めます。
スポンサーリンク
スポンサーリンク

Entityの存在意義と役割

Entityとは?

CodeIgniter4のEntityは、データベースから取得したデータをオブジェクト指向的に操作するための仕組みです。単なる配列やstdClassではなく、データのバリデーション・整形・ミューテーションを簡単に行えるのが特徴です。

なぜEntityを使うのか?

  • データの一貫性を保つ
    直接データを変更するのではなく、Entityを介して操作することで、バリデーションや加工処理を統一できる。
  • getter/setterの活用で安全性を向上
    getFullName() のようなカスタムメソッドを作成できるため、ロジックを一元管理しやすい。
  • データのミューテーション(変換)
    setPassword() でパスワードのハッシュ化を自動化するなど、データ変換を簡単に実装できる。

Entityの使用例

Entityクラスの作成

まずは、app/Entities/User.php にEntityクラスを作成します。

namespace App\Entities;

use CodeIgniter\Entity\Entity;

class User extends Entity
{
    // 自動的にキャストするフィールド
    protected $attributes = [
        'id'       => null,
        'username' => null,
        'email'    => null,
        'password' => null,
    ];

    // パスワードのハッシュ化
    public function setPassword(string $password)
    {
        $this->attributes['password'] = password_hash($password, PASSWORD_DEFAULT);
        return $this;
    }

    // フルネームを取得する例(仮)
    public function getFullName()
    {
        return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
    }
}

Entityをモデルと組み合わせる

次に、Entityを利用するために、UserModel にEntityクラスを設定します。

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    
    protected $returnType = 'App\Entities\User'; // ここでEntityを指定する
    protected $allowedFields = ['username', 'email', 'password'];

    // 自動的にタイムスタンプを更新
    protected $useTimestamps = true;
}

コントローラーでの使用例

use App\Models\UserModel;
use App\Entities\User;

$userModel = new UserModel();

// 新しいユーザーの作成
$user = new User();
$user->username = 'testuser';
$user->email = 'test@example.com';
$user->setPassword('securepassword');

$userModel->save($user);

setPassword() を呼ぶことで、自動的にパスワードをハッシュ化できます。

データ取得時の活用

$user = $userModel->find(1);
echo $user->getFullName(); // フルネームを取得

Entityを使わない場合との比較

Entityなし(配列ベースの管理)

$data = [
    'username' => 'testuser',
    'email' => 'test@example.com',
    'password' => password_hash('securepassword', PASSWORD_DEFAULT),
];

$userModel->insert($data);

この方法でも保存は可能ですが、ロジックをコントローラーに書いてしまうため、コードの再利用性や可読性が低下します。

Entityあり

Entityを使用すると、バリデーションやデータ変換を統一でき、オブジェクト指向的に管理できるため、スッキリしたコードが書けます。

まとめ

項目Entityを使用しない場合Entityを使用する場合
データ管理方法配列やstdClassで管理オブジェクトとして管理
データの変換コントローラー側で行うEntity内で統一管理
バリデーションコントローラーにロジックを書くEntity内で完結
可読性・再利用性コードが散らばりやすい一箇所に集約される

Entityを使うことで、データをオブジェクトとして扱い、バリデーションや整形を一元管理できるため、よりクリーンなコードを実現できます!

スポンサーリンク
CodeIgniter
フォローしてね
スポンサーリンク

コメント

タイトルとURLをコピーしました