Kohana’s ORM – a brief introduction
- Posted by dlib on February 14th, 2008 filed in Kohana, ORM
- 7 Comments »
Kohana’s ORM library raises a lot of questions on the forums and IRC so I’ll write a short tutorial as how to work with it. I’ll cover the basics and from then on you’re on your own.
Say we are building a site with tutorials and we need articles. We’d have to create a table for the articles, a model to retrieve and insert,update,delete them and a controller for the users to interact with. I won’t cover all grounds as this should be only an introduction so for example views and completely securing your application I won’t address.
First create the table:
CREATE TABLE IF NOT EXISTS `articles` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) character SET latin1 NOT NULL, `text` text character SET latin1 NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
This is as simple as they come. The autoincrementing ‘id’ field is required for the ORM to work as well as the plural table name ‘articles’. An
Now we have to create a model to interact with the table. The filename of the model is the singular so article.php We place this file in application/models
The file itself will look something like this:
class Article_Model extends ORM { //protected $belongs_to = array('users'); }
In this tutorial I won’t cover relationships but if you want them it should be done like seen in the inline comment.
This is all you need to get working on ORM in Kohana. It’s a breeze.
Now we need a controller. Let’s call ‘article’. Create a file ‘article.php’ in application/controllers and put the following code in there:
class Article_Controller extends Controller { public function index() { } public function insert() { } public function view() { } }
When we call http://localhost/article we end up in the index method, and localhost/article/insert get’s us to the insert method.
We want the index() method to list the last 10 articles and the insert() method speaks for itself. localhost/article/view/2 will show article with id=2
public function index() { $articles=new Article_Model(); $articles=$articles->orderby('id','desc')->limit(10)->find_all(); echo '<ol>'; foreach($articles as $article) { echo '<li>'.$article->title.'</li>'; } echo '</ol>'; }
You can see I load the Article_Model which is an ORM model. I ask it to retrieve 10 articles ordered descendingly by id. Note that I use db builder methods, this is what makes Kohana’s ORM quite powerful. The find_all method does the actual query and returns the result. Always put find or find_all last as it will start the query.
I then iterate over the result and format it into a nice ordered list. Normally this would be done in a view.
Now for the view() method, I want to call http://localhost/article/view/2 and then retrieve the article with id=2
public function view($id=1) { $article=new Article_Model($id); if($article->id== '' ) Event::run('system.404'); echo '<h1>'.$article->title.'</h1>'; echo ''.$article->text.''; }
I instantiate the model with the id and it will immediatly query the database for the record.If no arguments are given $id will be 1. If no article exists with the supplied id, say $id=10 a 404 event will be triggered launching the 404 page. Else the article is outputted:
Goodbye World
More of this and that
The most difficult method is the insert()
function insert() { $form=new Forge(); $form->input('title')->label(true); $form->textarea('text')->label(true); $form->submit('Submit'); if($form->validate()) { $article=new Article_Model(); $article->title=$form->title->value; $article->text=$form->text->value; if($article->save()) { echo 'Saved'; } } else { echo $form->html(); } }
I use the Forge module for Kohana to create the form. It should be easy to grasp for more information go to this page.
Anyway, once the form is submitted it will be validated, there are no rules so validation will succeed. Then I create a new Article_Model give its properties the right values taken from the $form object and save the Article_Model object into the database. Note: I do not check the variables for malicious things, this is not recommended.
This is it, it’s all relatively simple I think. I have a little encore. Say you know an article has a title ‘Hello World’ but that’s all you know.
public function hello_world() { $article=new Article_Model; $article->find_by_title('Hello World'); echo $article->text; }
Will output the article’s text.
This can be expanded by find_all_by, find_by_title_and_text, find_by_title_or_text, find_related etc.. see the ORM page for more information.
As announced, I did not coverrelationships. This maybe something for the future.
February 14th, 2008 at 2:05 pm
[...] have moved this tutorial to a new blog dedicated to Kohana Posted by nmweb on Monday, February 4, 2008, at 10:45 pm, and filed under English, [...]
February 15th, 2008 at 5:10 pm
Great article! I posted a link to this tutorial in the Kohana ORM user guide page: http://doc.kohanaphp.com/libraries/orm.
I think a follow-up that covers relationships would be great.
June 14th, 2008 at 6:45 pm
great post, like this kind of lightweight ORM without tons of XML files.
July 8th, 2008 at 4:14 am
Since there was no “Hello World” example on the Kohana site, I took this as the closest example I could find. However, when I built it, I only get 404 errors when trying to go to the pages. Is there a configuration step I am missing? How do I tell Kohana what models and views are available?
Or better yet, are there any better example Kohana applications that demonstrate basic functionality?
July 8th, 2008 at 1:04 pm
This tutorial assumes you have Kohana installed. I’ve linked at several occasions to guides to installing Kohana. Check the user guide for example. In your case install a .htaccess file
April 17th, 2009 at 9:32 am
$form=new Forge();
please correct this
June 5th, 2009 at 1:47 pm
[...] week and highly recommend checking it out. One of the features I’ve been most impressed by is ORM which uses SQL schema extrapolated from the source database to create a editable object that can [...]