Kohana ORM Tip : ORM Tree

Published on:
Tags: PHP, Personal

Well the last ORM tip seemed to get a bit of traffic so I thought I would throw another one together. This time it covers the little known ORM_Tree library. This is (IMO) a spectacular example of the flexibility and power of Kohana, by taking a look at this ORM extension (system/libraries/ORM_Tree) you can see quite how easily this age old storage pattern is solved by extending the ORM class.

Using it is even simpler!

Our Scenario
We want to implement a standard categories system in our site but not have to go through all the trouble of building it from scratch and would love to harness the existing power of the ORM library . .enter ORM_Tree

The table

CREATE TABLE `categories` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL default '',
  `parent_id` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`)
)

The Model

class Category_Model extends ORM_Tree
{
    protected $children = "categories";
}

Using it
To test this let’s add some test data;

  INSERT INTO `categories` VALUES (1,'root',0),(2,'beer',1),(3,'meat',1),(4,'pork',3),(5,'beef',3);

So after adding some appropriate information using it is as simple as..

  print_r(ORM::factory("Category", 1)->children->as_array());

…to return the children for the category with id 1

  echo ORM::factory("category", 4)->parent->name;

..would print the parent name of the category with ID 4

Hopefully that little tip will help someone! Any questions then please don’t hesitate to ask!

/Matt