Designing an ActionScript ORM
How do we get the best of DataMapper and ActiveRecord within the constraints of ActionScript?
First off, the design goals and desires:
Being a data model automatically allows Post objects to do database operations. There is one weakness, if you are a purist. Since ActionScript does not allow static methods of a class to be inherited, some methods (such as find and create) which make sense as class level static methods end up having to be defined as object methods.
For associations, I use reflection using a combination of class meta-data and the describeType functionality within the Flex framework. The declaration itself is straightforward.
Which means, you can now add, access, and update comments associated with the Post objects like so:
I really like Datamapper style declaration of fields and properties within the class definition. ActiveRecord does better with schema versioning and the ability to migrate selectively without loss of data and with optional data transforms. The ability to extend the schema during development, or as part of application updates is invaluable. This is how we handle it in our ActionScript ORM.
When necessary, additional migration functions can be added to the array of migrations. The Migrator tracks schema versions on a per-table basis to make sure changes are automatically reflected in the schema.
Finally, we utilize the ECMAScript prototype mechanism to set schema properties on each of the Modeler sub-classes, to allow usage such as this:
One more thing, add the following compiler setting.
- Easily create persistent objects that map to database storage.
- Flexible methods to abstract data manipulation and queries.
- Model DB associations through object properties and relations.
- Support run-time schema extensibility (migrations)
import com.memamsa.datamapper.*;
dynamic public class Post extends Modeler {
// Post objects are now DB models.
}[Association(name="comments", className="Comment", type="has_many")];
dynamic public class Post extends Modeler {
}var post:Post = new Post();
// add a new comment to the post
post.comments.push(new Comment({author: 'cooldude', text: '1st'}));
// how many comments do we have?
post.comments.list().length;
// find comments matching criteria
post.comments.find({conditions: 'author like %cool%', order: 'created_at ASC'});import com.memamsa.datamapper.*;
dynamic public class Post extends Modeler {
// describe the migrations
// The Migrator takes this class references, options and an array of
// migration functions.
private static const migrations:Migrator = new Migrator(
Post,
{id: true},
[
function(my:Migrator):void {
my.createTable(function():void {
my.column('title', DB.Field.VarChar, {limit: 128});
my.column('author', DB.Field.VarChar, {limit: 40});
my.columnTimestamps();
}
}
]);
//.. other class methods and properties...
}var p:Post = new Post();
p.load({id: 2});
p['title'] = 'New Title';
p.save();- -keep-as3-metadata+=Association