Doctrine ORM with CodeIgniter: Introduction

I’m currently developing a website for scheduling a volunteer group. (I’ll announce that in a separate entry). For this particular project, I chose the following:

I’m going to focus on the Doctrine integration for this entry. I got the idea to try Doctrine from Burak‘s blog “PHP and Stuff”. I started with this entry on using CodeIgniter with Doctrine.

The idea is this – If you’re already accessing objects in PHP to handle things like form validation, creating users, logging in, etc; why not use objects to represent your data as well? Doctrine provides a really nice framework to help do just that.

Typically, I would write my CodeIgniter Models to include a method for each operation I would need to perform on a particular type of data (Typical CRUD)

<?php
//methods in a user "model" in code igniter
function insert_user($data)
{
  //SQL code to insert a user
}
function update_user($data)
{
  //SQL code to update a user
}
function get_user($user_id)
{
  //SQL to get user info from the database
}
function delete_user($user_id)
{
  //SQL to delete a user
}

Doctrine does things a little differently. The “model” is really just a definition of the User database table and its relationships rather than an object containing the SQL itself. The Doctrine library provides all of the behind-the-scenes database interaction for you.

Let’s say I have a user is defined like so:

  • First Name
  • Last Name
  • Email Address
  • Favorite Color

In doctrine, I can simply define the User object

<?php
class User extends Doctrine_Record
{
  public function setTableDefinition()
  {
    $this->hasColumn('first_name','string',50);
    $this->hasColumn('last_name','string',50);
    $this->hasColumn('fav_color','string',50);
    $this->hasColumn('email','string',100,array('email' => TRUE, 'unique' => TRUE));
  }
}

that’s it! I don’t need to do anything else to peform all the CRUD operations on any users. To create a user:

<?php
$u = new User();
$u->first_name = 'Jon';
$u->last_name = 'Trelfa';
$u->email = 'user@example.com';
$u->fav_color = 'blue';
$u->save();

I don’t think I need to repeat much of what Burak and the Doctrine project have already documented – so I will end this introduction for now. Stay tuned as I document my discoveries :)

About Jon Trelfa

I live in Detroit, Mi.
This entry was posted in Code and tagged , . Bookmark the permalink.

One Response to Doctrine ORM with CodeIgniter: Introduction

  1. shin says:

    “I’m currently developing a website for scheduling a volunteer group. ” I am looking forward to your new application.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>