Still while work­ing on this app I was talk­ing about ear­lier I real­ized I was quite used to work­ing with PHP classes’ Magic Meth­ods, and more pre­cisely the way it han­dles over­load­ing. Those lovely __get, __set and __call meth­ods are called when­ever you try to access a property/method that is not explic­itly defined, mak­ing your class dynamic. Of course you don’t need this all the time, and it might even be dan­ger­ous, but it some cases that’s sim­ply perfect.

You can do that with AS3 if you extend flash.utils.Proxy, cool. But wait, no! Not cool! What if I wanted to extend some­thing else? Nah, let’s find some­thing else…

I came up with the idea of dynam­i­cally cre­at­ing get­ter and set­ter func­tions on a class instance for pre­de­fined properties. Now those aren’t really get­ters and set­ters but let me show you what it looks like so you under­stand bet­ter… Here’s an example:

package {
	import net.tw.util.Dynam;
	// This is my class, that has to be dynamic
	public dynamic class DynClass {
		// This Array will be used to store the properties' values...
		protected var _data:Array=[];
		public function DynClass() {
			// In the constructor I call the Dynam.ize method on this, so it builds the getters and setters for the supplied properties
			Dynam.ize(this, ['abc', 'def', 'ghi'], getter, setter);
		}
		// Here are the functions that will be called when I try to get or set one of the properties I listed in Dynam.ize
		protected function getter(key:String):* {
			return _data[key];
		}
		protected function setter(key:String, v:*):void {
			_data[key]=v;
		}
	}
}

Now let’s instan­ti­ate this class and play with it:

var dc:DynClass=new DynClass();

We can call getAbc() or setAbc() on it:

dc.setAbc('my value');
trace('get abc', dc.getAbc());

Every­thing should be OK. It would work the same with get/setDef and get/setGhi… This exam­ple might not seem very use­ful but you could do any­thing within the get­ters and set­ters ; for exam­ple access Share­dOb­jects, send­ing data to a server and so on…

Find the class and a demo project on as3-bits!

Com­ing up next: my imple­men­ta­tion of this con­cept for AIR’s SQLite databases!

Thoughts?