Ticket #85 (new enhancement)

Opened 4 years ago

Last modified 2 years ago

Implement Polymorphic associations

Reported by: bermi Assigned to:
Priority: major Milestone: 2.0
Component: Active Record Keywords:
Cc:

Description

Implement Polymorphic Associations

Polymorphic associations will link objects of different types with common characteristics but different representations.

Having in our installer

function up_1(){
    $this->createTable('catalog_entries', 'id, name, resource_type, resource_id, created_at, updated_at');
    $this->createTable('images', 'id, content, created_at, updated_at');
    $this->createTable('sounds', 'id, content, created_at, updated_at');
    $this->createTable('article', 'id, content, created_at, updated_at');
}

by having polymorphic associations we can avoid the need for a table like

# This should be avoided with polymorphic associations
$this->createTable('catalog_entries', 'id, name, image_id, sound_id, article_id, created_at, updated_at');

In order to use polymorphic associations our models for the previous installer would look like

class CatalogEntry extends ActiveRecord{
    var $has_one = array('resource' => array('polymorphic' => true));
}

class Image extends ActiveRecord{
    var $has_one = array('catalog_entries' => array('as' => 'resource'));
}

class Sound extends ActiveRecord{
    var $has_one = array('catalog_entries' => array('as' => 'resource'));
}

class Article extends ActiveRecord{
    var $has_one = array('catalog_entries' => array('as' => 'resource'));
}

In order to assign an Image to the Catalog we will do

$Entry = new CatalogEntry(array('name' => 'Nice Image'));
$Entry->resource->assign( new Image(array('content' => 'binary data')) );
$Entry->save();

We can retrieve entries by

$Entry = $CatalogEntry->findFirstBy('name', 'Nice Image', array('include'=> 'resource'));
$Entry->resource->get('content'); //=> binary data

$Entry->resource will hold an instance of the associated type.

This is a first draft in how I would like polymorphic associations in Akelos, feel free to suggest or criticize this approach.

If you feel you can help with this, please feel fee to contribute your code, but remember to announce first in the comments that you want to code this piece of code so we can avoid doing the work twice.

Change History

12/19/09 21:55:09 changed by bermi

  • milestone changed from 1.0.1 to 1.3.0.

12/19/09 21:55:20 changed by bermi

  • milestone changed from 1.3.0 to 2.0.