William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP: another way to implement ORM

ORM: Object vs. Associate Array

I want to do ‘DB tables‘ <==> ‘PHP Objects‘ mapping, to extract some common features between them. Here are the 2 choices:

(1) Use a class to reflect a DB table:
Traditionally, the ORM (Object-Relational Mapping) uses a object to map DB table:
  (a) properties – exact the same as corresponding DB table column definition;
  (b) methods – POJO style getters and setters to represent persistent column objects.
(2) Use an associate array to reflect a DB table:
Also, plain config file can be used to represent a DB table, instead of a class model.
This is my way for the quick solution.
PHP provides easy-use and powerful functions to operate config file, such as parse_ini_file() , to get the table information in an associate array.

The following I list some disadvantages of using ORM class model:

1. SQL is separated and divided everywhere.
The nature SQL relationships are damaged, that means it is hard to get benefits of native SQL features. E.g., in doctrine document, generally each OneToOne or ManyToOne Relation in the Database is replaced by an instance of the related object in the domain model. Each OneToMany or ManyToMany Relation is replaced by a collection of instances in the domain model. You never have to work with the foreign keys, only with objects that represent the foreign key through their own identity.
2. The codes become very difficult to trace/debug if you want to find what hell SQL actually is.
3. Low performance and hard to optimize.
It is no doubt that DB object model mappings will lost benefits of performance.
For example, the ORM has POJO (Plain Old Java Objects) to be the persistent API. POJO are the Objects with just getters and setters, often used in domain modelling.
So in the mapping class, there are a lot of getters, setters; SQL are hidden; all objects methods have to do SQL convertion each time; for complex SQL, it would be disaster to assembly the SQL.
4. Hard to integrate with 3rd library, such as jQuery & plugins, AJAX.
5. It is not Intuitive, very difficult to modify and extend compared to pure SQL.

The following codes I get from Doctrine, which is a start-level introduction of this famous PHP ORM.
For a simple User class, a tedious class to create to represent a DB table:

class User {
 protected $id;
 public $name;

 public function getId(){
  return $this->id;
 }

 public function getName(){
  return $this->name;
 }

 public function setName($name){
  $this->name = $name;
 }
}

With this definition and Doctrine Object Relational Mapper‘s help, the following OO method works:

$newUsername = $argv[1];
$user = new User();
$user->setName($newUsername);
echo "Created User with ID " . $user->getId() . "\n";

It is pretty bored, lack of flexible, and inconvenient; if you are good at SQL, you never think about to do DB operation like that: for a simple ‘insert into Users()’, they do a large Circling to get there, stupid, eh?

using Associate Array/flat config file to implement ORM

As a experienced programmer, I use as many as possible array/associate array/hash tables in my codes, they relief me quite a lot, make my work easier and high performance. Using array/associate arry are always good choices, plus some supplements, such as Regular express, $_SESSION, and jQuery, you can implement everything, quick and efficient.

ORM object-based solution is not my first choice, so I use Array instead. It works pretty well, overcome above disadvantages of class models.

The implementation are pretty simple and intuitive. The following are advantages:

  • Manually add/modify table information into a config file. Pretty easy. Compared to ORM mapping (write class, setters, getters…), it walks in a straight way, not a big cycle.
  • Parse the table information into arrays. These arrays belong to this class, So each class represents a DB table, and pocessing common and specific features for this table.
  • Common classes are build to process universal features: such as CRUD, List, sorting, pagination, edit form, export reports, etc. different classes will share these common web features by inheritance these classes, in other words, individual class and table are transparent, no matter what data resources, all these common features () are available for them.
  • For some specific features in a individual class, it can implement by itself, e.g., some class has the feature of WYSIWYG, some needs multi-files upload.

Here is a quick implement: I transfer my wordpress blog into this array-based ORM, what I did is manually edit the config file, no PHP codes touched. For different tables, it works the same way: just add entry into config file! The following is a snippet section of this config file, pretty easy to understand:

[wordpress_table_information]
table_name = wp_posts
primary_key = ID
type = int

[wordpress]
ID = id
post_author = post_author
post_date = post_date
post_content = post_content
post_title = post_title
post_status = post_status
post_name = post_name
post_type = post_type,post_size,post_mime_type
comment_count = comment_count

[wordpress_column_types]
post_name = text
post_content = textarea

The explaination of the config file:

1. wordpress_table_information
The table information: name, primary key & type, foreign key & type
2. wordpress
What columns in the table to be list in web? the comma ‘,’ means to list 2(or more) columns in a row.
3. wordpress_column_types
Normally, all the table columns are list as plan html text; for some reasons(update column, better display, link), some columns need specific indicating: in here, the text and textarea are to indicate these columns are <inpt type=”text” > and <textarea>

The core part is to parse the config file and setup an array to hold the table information:

function get_mappings($section=NULL, $map_file=NULL)
{
 // which section to parse? by default it is the section with same name of the class instance.
 if(! $section) $section = $this->self;
 // which configure file is used? use macro definition.
 if(! $map_file) $map_file = MAP_FILE;
 // set a back-door.
 if(isset($this->map_file)) $map_file = $this->map_file;

 // if class array 'ini_array' is empty, do parse_ini_file().
 if (count($this->ini_array)==0) {
  if (file_exists($map_file)) {
   $this->ini_array = parse_ini_file($map_file, true);
  }
  else {
   die('No MAPPINGS FILE: ['.$map_file.']: ' . __FILE__ .'->'. __LINE__);
  }
 }
 // class property ini_array hold all the parsed configure information,
 // return the array of this class needs.
 if(array_key_exists($section, $this->ini_array))
  return $this->ini_array[$section];
 else return;
}

Here, parse_ini_file is very useful: it likes a ORM convertion, converts DB table to array.

After the parse, we get an associated array:

array(
  'wordpress_table_information' => array(
    'table_name' => wp_posts
    'primary_key' => ID
    'type' => int
  ),
  'wordpress' => array(
    'ID' => id
    'post_author' => post_author,
    'post_date' => post_date,
    'post_content' => post_content,
    'post_title' => post_title,
    'post_status' => post_status,
    'post_name' => post_name,
    'post_type' => 'post_type,post_size',
    'comment_count' => 'comment_count',
  ),
  'wordpress_column_types' => array(
    'post_name' => text,
    'post_content' => textarea
  ),
);

By using PHP powerful array-functions, it becomes possible to process and present any kind of data.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: