CodeIgniter Tutorial – ORM with DataMapper

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

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.

<?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

<?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

<?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

<?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

<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#2
  3. CodeIgniter Tutorial – To do list application part 3
  4. CodeIgniter Tutorials to Help You Get Started
  5. CodeIgniter Tutorial Compilation

Tags:

13 Responses to “CodeIgniter Tutorial – ORM with DataMapper”

  1. [...] More: CodeIgniter Tutorial – ORM with DataMapper | KomunitasWeb [...]

    Pingback by CodeIgniter Tutorial - ORM with DataMapper | KomunitasWeb « live.exofire.net — April 2, 2009 @ 11:36 am

  2. the title got me for a moment, i thought the datamapper project for ruby.

    ah that looks cool :)

    Comment by taylor.luk — April 2, 2009 @ 5:54 pm

  3. Why is some code in php4 (var) and other in php5 (__construct) ??

    Comment by AntonioCS — April 3, 2009 @ 4:02 am

  4. @AntonioCS Thanks for pointing me out. It’s no problem and run well, but I see your point, it’s bad practice. I have changed my code now.

    Comment by Gilang Chandrasa — April 3, 2009 @ 5:31 am

  5. Great tutorial. Will add to http://tutlist.com

    Comment by JDStraughan — April 3, 2009 @ 9:14 am

  6. Great tutorial :)

    p.s. Where is Berbatov ?!

    Comment by Radoslav Stankov — April 3, 2009 @ 4:36 pm

  7. nice tutorial !
    Do u have any other tutorials that using another ORM other than Datamapper ?

    Comment by oDiN — April 4, 2009 @ 10:40 am

  8. [...] April 5 2009 Zaki saved CodeIgniter Tutorial – ORM with DataMapper | KomunitasWeb on Delicious. 02:00 am – No [...]

    Pingback by links for 2009-04-04 — Mior Muhammad Zaki: PHP & JavaScript Programmer — April 4, 2009 @ 12:01 pm

  9. [...] Komunitasweb.com today there’s new tutorial showing how to use the DataMapper library for the CodeIgniter framework to introduce object [...]

    Pingback by Komunitasweb.com: CodeIgniter Tutorial - ORM with DataMapper | Cole Design Studios — April 6, 2009 @ 7:08 am

  10. [...] http://komunitasweb.com/2009/04/codeigniter-tutorial-orm-with-datamapper/ [...]

    Pingback by CI « H79.de — April 6, 2009 @ 3:18 pm

  11. Good tutorial. Problem though. Using CI 1.7.1, php5. pagination link to page 2 not working. Also, do you have style.css? Thanks for the tutorial.

    Comment by al — April 16, 2009 @ 5:49 am

  12. Nice tutorial..

    @al : I had the same problem like yours, and I changed :

    $config['base_url'] = site_url(“students”);
    $config['total_rows'] = $total_rows;
    $config['per_page'] = ’5′;
    $config['uri_segment'] = 2;
    $this->pagination->initialize($config);

    to:

    $config['base_url'] = site_url(“students/index”);
    $config['total_rows'] = $total_rows;
    $config['per_page'] = ’2′;
    $config['uri_segment'] = 3;
    $this->pagination->initialize($config);

    and it works great..

    Comment by gowar — April 18, 2009 @ 11:27 am

  13. This is really cool. Am i supposed to write a model like StudentsCourses or the DataMapper is taking care of that too?

    Comment by Zoran — April 21, 2009 @ 12:47 pm

Additional comments powered by BackType