Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Object Relation Mappers

Featured Replies

Hi guys, I thought I'd have a stab at creating my own blog article on WDF but the blog function doesn't seem to work for me so I'll just post it up here. Seeing as ORM's have been mentioned a few times on the forum recently, and some people have expressed and interest in learning Doctrine/Propel, I thought I'd write a quick article on how to create your own Object Relation Mapper using PHP. This isn't the full write up, its just some of the code for you to have a look at. Any copy and paste cowboys should be aware that you'll need PDO with sqlite & PHP 5.3 to use my code.

 

Firstly our entity manager...

class EntityManager extends PDO
{
   private function prep(&$field)
   {
           $field = ':'.$field;
   }

   public function find($table, $id)
   {   
       $stmt = $this->query('SELECT * FROM '.strtolower($table).' WHERE id = :id ;');
       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
       $stmt->execute();
       return $stmt->fetchObject(ucfirst($table));
   }

   public function persist($obj)
   {

       if(is_object($obj)) {
           $reflect = new ReflectionClass($obj);
           $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);

           $fields = array();

           foreach ($props as $prop) {
               if(!empty($obj->{$prop->getName()})) {
                   $fields[] = $prop->getName();
               }
           }

           $it = new ArrayIterator($fields);

           $query = 'INSERT OR REPLACE INTO '.strtolower(get_class($obj)).' ('.implode(', ', $fields).') VALUES (';
           array_walk($fields, array($this, 'prep'));           
           $query .= implode(', ', $fields).');';

           $stmt = $this->prepare($query);

           foreach($it as $field) {
               $stmt->bindParam(':'.$field, $obj->$field);
           }

           if($stmt->execute()) {
               return $this->find(get_class($obj), $this->lastInsertId());
           } else {
               return false;
           }
       }
   }
}

 

This object is basically PDO but with 2 extra functions, find() which will find a record by id and hydrate the relevant object. And persist, which will 'save' a model to the database. Obviously in practice the find function would be a lot more robust with exception catching. I probably should have used question marks in my query as it would have saved a few lines of code but it doesn't really matter.

 

Anyway thats the business side of things done, the next step is to create our entity/model, as you can see from my user model below, each class property reflects a database column. This is the most basic form of mapping, and doesn't provide the ORM with and column data. But this is just for demonstration purposes. If you were to supply column data somehow, you could read that data and use it to automatically prepare statements, validate data, etc.

 

class User
{
   public $id;

   public $username;

   public $password;

   public $f_name;

   public $s_name;    

   public $created_at;

   public function getDate()
   {
       return new DateTime($this->created_at);
   }

   //take from php docs comments
   private function pluralize( $count, $text )
   {
       return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
   }    

   //take from php doc comments
   public function memberFor()
   {
       $created = $this->getDate();

       $interval = date_create('now')->diff($created);

       if ( $v = $interval->y >= 1 ) return $this->pluralize( $interval->y, 'year');
       if ( $v = $interval->m >= 1 ) return $this->pluralize( $interval->m, 'month');
       if ( $v = $interval->d >= 1 ) return $this->pluralize( $interval->d, 'day');
       if ( $v = $interval->h >= 1 ) return $this->pluralize( $interval->h, 'hour');
       if ( $v = $interval->i >= 1 ) return $this->pluralize( $interval->i, 'minute');

       return $this->pluralize( $interval->s, 'second' ) . $suffix;        
   }

   public function getFullName()
   {
       return $this->f_name . ' ' . $this->s_name;
   }
}

 

As you can see I've added some basic userland functions to the object to demonstrate the power of using entities/models in your applications.

 

OK now we can pull it all together...

 

//create new entity manager
$db = new EntityManager("sqlite::memory");

//create a demonstration table
$db->exec('CREATE TABLE "main"."user" ("id" INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL , 
"username" VARCHAR, 
"password" VARCHAR,
"f_name" VARCHAR,
"s_name" VARCHAR,
"created_at" DATETIME DEFAULT CURRENT_TIMESTAMP)');

//populate table
$db->exec('INSERT INTO user (username, password, f_name, s_name, created_at) VALUES (\'johng\', \'eD9AD0dz7\', \'John\', \'Guthrie\', \'2011-01-01 01:00:00\');');

// get an existing user
$user = $db->find('User', 1);

echo '<p>'.$user->getFullName() . ' has been a member for ' . $user->memberFor().'</p>';

// create a new user
$user = new User();
$user->f_name = 'Robert';
$user->s_name = 'Burns';
$user->username = 'robertb';
$user->password = 's£fvdS4sa!';

//save user and re-hydrate model
$user = $db->persist($user); //look no SQL!

//check to make sure our data saved...
$sth = $db->prepare("SELECT * FROM user");
$sth->execute();
$result = $sth->fetchAll();
echo '<pre>';
print_r($result);
echo '</pre>';

//house keeping
$dump = $db->prepare("DROP TABLE user;");
$dump->execute();

 

Thats pretty much it, an ORM in less than 150 lines of code. Worth pointing out that typically a persist function wouldn't return any data (replicating a database insert), that would be the responsibility of a re-hydrate function. I just made it re-hydrate the model in here to keep it simple. Any feedback is welcome, when the blogs work again I might post up a better writeup.

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.