Still while working on this app I was talking about earlier I realized I was quite used to working with PHP classes’ Magic Methods, and more precisely the way it handles overloading. Those lovely __get, __set and __call methods are called whenever you try to access a property/method that is not explicitly defined, making your class dynamic. Of course you don’t need this all the time, and it might even be dangerous, but it some cases that’s simply 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 something else? Nah, let’s find something else…
I came up with the idea of dynamically creating getter and setter functions on a class instance for predefined properties. Now those aren’t really getters and setters but let me show you what it looks like so you understand better… 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 instantiate 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());
Everything should be OK. It would work the same with get/setDef and get/setGhi… This example might not seem very useful but you could do anything within the getters and setters ; for example access SharedObjects, sending data to a server and so on…
Find the class and a demo project on as3-bits!
Coming up next: my implementation of this concept for AIR’s SQLite databases!
Thoughts?