Kohana ORM Tip

Published on:
Tags: Kohana, PHP

Well, I havn’t posted anything for a little while, what with work, work and even some personal things i’ve been working on time just seems to of evapourated.

During the time Kohana 2.2 has been released, congratulations to everyone involved in that, there now seems to be the slow but inevitable move towards bringing the documentation up to date. Im hoping that I will find the time to put together a few tutorials soon to show of some of the new features in Kohana, and with even more hope I will be releasing a couple of small apps (fngers crossed)

So in an attempt to kick things off I thought I would mention a small but often overlooked feature of the ORM library: unique_key.

The orm library provides a function within it called unique_key, which is primarily meant to be overloaded by any extending classes, by overloading this method we have the ability to load models based on any unique field in our table.

For instance:

$a = new Blog_Model(1);

The above will load a blog model with an ‘id’ field (our primary key) value of 1, all very standard. What if each blog had a ‘slug’ field, this slug was a user readable/friendly unique attribute given to each blog post, wouldnt it be great if we could load a blog post by this attribute? . .well we can with the unique_key function!

public function unique_key($id)
    if(is_string($id) AND ! ctype_digit($id))
        //the id passed to the constructor was a string
        return 'slug';
    //default to returning the standard orm field ('id')
    return parent::unique_key($id);

With this function in our Blog_Model class we can now do the following:

$a = new Blog_Model("user_friendly_blog_name");

A very nice little piece of functionality, bear in mind though that you must ensure that the field returned by unique_key must be unique in your system in order to be effective.

Hope that helps someone!