DataMapperことはじめ

DataMapperとは

CodeIgniter2.x用のORMライブラリ。
http://datamapper.wanwizard.eu/index.html

  • 特徴
    • 導入・設定が簡単
    • 各プロパティのバリデーションが可能
    • 1対1, 1対多, 多対多のリレーションをサポート
    • (CodeIgniterの)ActiveRecordライクなデータセレクトが可能

CodeIgniterのActiveRecordクラスと比較すると、3番目のn対nのリレーションを自動的に扱ってくれる点が優れている。
いちいちJOINを書くのはだるいです。

基本的な使い方(モデル編)

<?php
class Student extends DataMapper {
}

基本的にはこれだけで使える。
本家本元のActiveRecordと同じく、Studentモデルはstudentsテーブルを参照する。(=モデル名を複数形にしたテーブルを参照する)


クラス変数tableを定義することで、参照先テーブルは変更可能。

<?php
class Student extends DataMapper {
	var $table = 'students';
}


バリデーション、リレーション、クラスメソッドなども書ける。

<?php
class Student extends DataMapper {
    // リレーション
    var $has_many = array('team');
    // バリデーション
    var $validation = array(
        'name' => array(
            'label' => 'Student',
            'rules' => array('required', 'trim', 'unique', 'alpha_dash', 'min_length' => 1, 'max_length' => 50),
        );
    // クラスメソッド
   function hoge {
      // something do
   }
}

基本的な使い方(コントローラー編)

<?php
class Test extends CI_Controller {

    function __construct() {
        parent::__construct();
        
    }
    
    function index() {
       // $this->load->model('student');
        
       $student_model = new Student();
       $student = $student_model->get_by_id(1);
    // 以下の書き方でもOK
       // $this->load->model('student');
       // $student = $this->student->get_by_id(1);
    echo $student->name;
    }
}

リレーションシップについて

studentsテーブル

id name
1 田中
2 北嶋
3 大津
4

temas

id name
1
2 広島

teams_and_studentsテーブル

team_id student_id
1 1
1 2
1 3
1 4
2 4

こんな感じでStudentモデルとTeamモデルの間に多対多の関係があるとする。
モデルとコントローラーは以下のように書ける。

<?php
class Student extends DataMapper {
 
    var $has_many = array(
        'teams' => array(
            'class' => 'team', // リレーション先のクラス(モデル)を指定
	  'join_table' => 'teams_and_students', // JOIN用テーブル名を指定
            'join_other_as' => 'team_id', // リレーション先のIDを指すカラム名を指定
            'join_self_as' => 'student_id', // 自身のIDを指すカラム名を指定
			'auto_populate' => TRUE // リレーションの自動取得を有効に
           )	
    );
<?php

class Test extends CI_Controller {

    function __construct() {
        parent::__construct();
        
    }
    
    function index() {
       $this->load->model('student');
       $student = $this->student->get_by_id(4);
       
       foreach($student->temas as $team)
       {
           echo $team->name . "<br/>";
       }
    }
}

おまけ

DataMapperの日本語用設定ファイルを書いた。
https://github.com/ninoseki/sparks-datamapper