ORM: Tips and tricks
- Posted by dlib on March 31st, 2008 filed in Code examples, Medium, ORM
Several posts already covered the usage of Kohana’s ORM. It’s basic usage should now be a little clearer I hope. I hope to deal with relationships a little more but that’s for a later time. For now I want to share some simple tips and tricks that might be handy but not that apparent for those starting with Kohana.
Say your Article_Model which extends ORM has a modified and a created datetime field in MySQL. It could also be a timestamp field or any other date or time field. As illustrated in an earlier post you adapt the save() of ORM so the modified field is changed on updates and the created field on inserts.
However, you want to retrieve this data from your database to show a nicely formatted (localized) date in your application. Each time you retrieve it you must do a strtotime() for the conversion from MySQL to php. Until you’ve seen this little trick.
class Article_Model extends ORM{ public function __get($key) { if($key=='modified' || $key=='created') { if (isset($this->object->$key)) { return strtotime($this->object->$key); } } return parent::__get($key); } }
Now, every time you retrieve any of those fields it is converted to a php timestamp.
Another usage of this is when you need to store objects or arrays in your database (for whatever reason).
public function __get($key) { if($key=='userobject' ) { if (isset($this->object->$key)) { return unserialize($this->object->$key); } } return parent::__get($key); } public function __set($key, $value) { if($key=='userobject') { $value=serialize($value); } return parent::__set($key,$value); }
See, now you can add objects to your database without worrying about serialization. This method lends itself to other uses as well. You could for example do the hashing of a password in the __set. Stuff like this keeps your controllers clean and to the point. Since you do it in the model it is reusable throughout your application. Do you know other ways to do these kinds of nifty things? Drop a comment!
September 8th, 2008 at 6:43 pm
Thanks for this tip. I do prefer to use native database date fields too.