CodeIgniter Tutorial – ORM with DataMapper

April 2nd, 2009

datamappertutorial

If you familiar with CodeIgniter, then you have realized by now that you can’t have relationship manager.

Yes, CodeIgniter doesn’t have built-in ORM. But there are several projects such as IgnitedRecord and DataMapper that will help you manage relationship between your models.

In this tutorial, I will introduce you to DataMapper.

From DataMapper Website

DataMapper is an Object Relational Mapper written in PHP for CodeIgniter. It is designed to map your Database tables into easy to work with objects, fully aware of the relationships between each other.

Features

  • Everything is an object!
  • Easy to setup, easy to use.
  • Custom Validation on object properties.
  • Lazy Loading (related objects are only loaded upon access).
  • Relations and their integrity are automatically managed for you.
  • One to One, One to Many, and Many to Many relations fully supported.\
  • Select data in the style of Active Record (with or without Method Chaining).

Ok let’s start our journey.

Installation

  1. Download DataMapper here.
  2. Extract the package.
  3. Copy application/config/datamapper.php file to your CodeIgniter application/config folder.
  4. Copy application/libraries/datamapper.php file to your CodeIgniter application/libraries folder.
  5. Copy application/languages/english/datamapper_lang.php file to your CodeIgniter application/language/english folder.
  6. Open your CodeIgniter application/config/autoload.php file and add the database and datamapper libraries to the autoload libraries array.
    $autoload['libraries'] = array('database', 'datamapper');

Case

Let’s have a case here. We have students and their courses. A student can have many courses, and a course can be chosen by many student.

Here our sample data look like.

Name Course
Carrick Sistem Basis Data
Evra Kalkulus II
Ferdinand Aljabar Linear
Sistem Basis Data
Sistem Informasi Manajemen
Hargreaves Jaringan Komputer
Kalkulus I
O’Shea Jaringan Komputer
Kalkulus I
Sistem Informasi Manajemen
Ronaldo Sistem Basis Data
Sistem Informasi Manajemen
Sistem Penunjang Keputusan
Rooney Sistem Informasi Manajemen
Tevez Jaringan Komputer
Kalkulus I
Vidic Jaringan Komputer
Sistem Basis Data

SQL Query for sample data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
CREATE TABLE IF NOT EXISTS `courses` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL,
  PRIMARY KEY  (`id`)
);
 
INSERT INTO `courses` (`id`, `name`) VALUES
(1, 'Jaringan Komputer'),
(2, 'Sistem Basis Data'),
(3, 'Sistem Informasi Manajemen'),
(4, 'Aljabar Linear'),
(5, 'Kalkulus I'),
(6, 'Kalkulus II'),
(7, 'Sistem Penunjang Keputusan'),
(8, 'Web Programming');
 
CREATE TABLE IF NOT EXISTS `courses_students` (
  `student_id` INT(11) NOT NULL,
  `course_id` INT(11) NOT NULL,
  PRIMARY KEY  (`student_id`,`course_id`)
);
 
INSERT INTO `courses_students` (`student_id`, `course_id`) VALUES
(1, 1),
(1, 2),
(2, 2),
(2, 3),
(2, 4),
(3, 1),
(3, 3),
(3, 5),
(4, 6),
(5, 2),
(6, 2),
(6, 3),
(6, 7),
(7, 1),
(7, 5),
(8, 3),
(9, 1),
(9, 5);
 
CREATE TABLE IF NOT EXISTS `students` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL,
  PRIMARY KEY  (`id`)
);
 
INSERT INTO `students` (`id`, `name`) VALUES
(1, 'Vidic'),
(2, 'Ferdinand'),
(3, 'O''Shea'),
(4, 'Evra'),
(5, 'Carrick'),
(6, 'Ronaldo'),
(7, 'Hargreaves'),
(8, 'Rooney'),
(9, 'Tevez');

Model

Let’s create some models now. Here is an example of what such a model class might look like when using DataMapper.

1
2
3
4
5
6
7
8
9
10
<?php
class Model_name extends DataMapper {
 
    public function __construct()
    {
        // model constructor
        parent::__construct();
    }
}
?>

Ok let have our model in DataMapper class

Student can have many course, so we set has many variable in student class.
application/models/student.php

1
2
3
4
5
6
7
8
9
10
11
12
<?php
class Student extends DataMapper {
 
    public $has_many = array('course');
 
    public function __construct()
    {
        // model constructor
        parent::__construct();
    }
}
?>

Course can be chosen by many student, so we also have has many variable in course class.
application/models/course.php

1
2
3
4
5
6
7
8
9
10
11
12
<?php
class Course extends DataMapper {
 
    public $has_many = array('student');
 
    public function __construct()
    {
        // model constructor
        parent::__construct();
    }
}
?>

Controller

In controller, we load URL helper, and pagination library.
application/controllers/students.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
class Students extends Controller {
 
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Student');
 
        // load url helper
        $this->load->helper('url');
 
        // load session library
        $this->load->library('pagination');        
    }
 
    function index($offset=0)
    {         
        $student_list = new Student();
        $total_rows = $student_list->count();
 
        $student_list->order_by('name');        
        $data['student_list'] = $student_list->get(5, $offset)->all;        
 
        // pagination        
 
        $config['base_url'] = site_url("students");
        $config['total_rows'] = $total_rows;
        $config['per_page'] = '5';
        $config['uri_segment'] = 2;
        $this->pagination->initialize($config);         
 
        $this->load->view('student/index', $data);        
    }   
}
?>

View

In the view, add pagination at the bottom of the table. And I add some logic to give zebra table effect.
application/views/student/index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<html>
    <head>
        <title>CodeIgniter Sample Application</title>
        <link rel="stylesheet" type="text/css" media="screen" href="<?= base_url() ?>css/style.css">
    </head>
<body>
 
<div id="container">
 
<h1>Datamapper Tutorial</h1>
 
 
<table>
	<thead>
	<tr>
		<th>Name</th>
		<th>Course</th>
	</tr>	
	</thead>
	<tbody>
	<?php $ctr = 0; ?>
	<?php foreach($student_list as $student): ?>	
	<?php $student->course->get()->order_by('name'); ?>
	<?php $ctr++ ?>
	<?php if ($ctr % 2): ?>
 	<tr>
		<td><?= $student->name ?></td>
		<td>
		    <? foreach($student->course->all as $course): ?>
		    <?= $course->name ?><br/>
		    <? endforeach ?>
		</td>
	</tr>	
	<?php else: ?>
 	 <tr class="odd">
		<td><?= $student->name ?></td>
		<td>
		    <? foreach($student->course->all as $course): ?>
		    <?= $course->name ?><br/>
		    <? endforeach ?>
		</td>
	</tr>	
	<?php endif; ?>
	<?php endforeach ?>
	</tbody>
</table>
 
 
<p class="pagination"><?= $this->pagination->create_links(); ?></p>
 
</div>
 
</body>
</html>

That’s it, you can see the demo here.

Don’t miss a thing, subscribe to our feeds.

More information

Related posts:

  1. Codeigniter tutorial – To do list application
  2. CodeIgniter Tutorial – To do list application part 3
  3. CodeIgniter Tutorial – To do list application#2
  4. CodeIgniter Tutorials to Help You Get Started
  5. CodeIgniter Tutorial Compilation

Tags:

13 Comments