Gallery3:Developer Handbook:ORM - Gallery Codex
Personal tools

Gallery3:Developer Handbook:ORM

From Gallery Codex

Revision as of 13:18, 13 June 2011 by Ckdake (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Object Relational Mapping (ORM)

Gallery 3 takes advantage of Kohana’s ORM library. This is a powerful abstraction that lets you treat a row in the database as an object in PHP. The object is defined by the SQL table definition with a strict correspondance between the ORM name and the table in the database. Once this mapping has been created, you can do most create, read, update and delete operations on an ORM instance without touching any SQL.

The bulk of data operations in Gallery 3 are done using ORM for simplicity. However when operating across many rows in the database at once, ORM can be very inefficient. In those cases, you may wish to use the Database Builder and create custom SQL queries. Almost all models in Gallery 3 are instances of the ORM class.

To create and use your own ORM, you’d start by creating a database table in your module installer. The tag module installer creates a table in the database with code like this (found in modules/tag/helpers/tag_installer.php):

 $db = Database::instance();
 $db->query("CREATE TABLE IF NOT EXISTS {tags} (
              `id` int(9) NOT NULL auto_increment,
              `name` varchar(128) NOT NULL,
              `count` int(10) unsigned NOT NULL DEFAULT 0,
             PRIMARY KEY (`id`),
             UNIQUE KEY(`name`))
             DEFAULT CHARSET=utf8;");

Note that the table name is plural and prefixed in this database query. The tag module has a model in modules/tag/models/tag.php like this:

 class Tag_Model_Core extends ORM {
 }

Now any code in the tag module can create a new tag like this:

 $tag = new Tag_Model();  // or ORM::factory(“tag”)
 $tag->name = “My Tag”
 $tag->save();

To load a tag with a given id, you can do a simple query for it:

 $tag = ORM::factory(“tag”)->where(“id”, “=”, 123)->find();
 if ($tag->loaded()) {
   // found it!
 }

Note that when you refer to an ORM, it’s in the singular (“tag”) whereas the table name in the database is always plural (“tags”).

advertisements