Mr Data Goes to Town
A plugin is persistent as the MANAGER class instantiates each of the plugins at the beginning of the transaction and holds them until the script completed execution.
From looking into many plugins, here's I tried to summarize some tricks for storing data through out execution.
Method 1: $this object
We can dynamically create variables as the plugin is being executed, this take advantage of the fact that MANAGER class holds on to the plugin object until the execution is done:
$this->new_var = 6542;
Method 2: global variable
This is the good old always working way of making data persistent. But depends on who you talk to, they will tell you global is bad bad bad boy that you shall not use. But hey, if you know what you're doing, why not?
(Note: Personally, I try to avoid global whenever possible... [update]see karma's comment below why we should not use global[/update])
global $my_global;
$my_global = 20;
Another question is what is the strategy for initializing persistent data in a plugin?
I assumed you can do it at the beginning of doSkinVar() or whenever needed. However, I saw code uses either init() or the class constructor function. Either way should be fine and are recommanded so all persistent data are initialized at the same place, for neatness's sicks.
Comments
hcgtv wrote:
karma wrote:
The main problem with globals arrises when two plugins decide to use the same global variable for different purposes
$this->foo is the cleanest way to persist data within a request. Initializing them in the constructor or init functions is a good thing and can prevent errors (Q: why the init function if you can do the same in the constructor? A: In the constructor, important thing like $this->plugid are not yet set, which means you can't call methods like getPluginOption)
$_SESSION could be used for session-specific data (actually, this is also a global variable so name-clashes might happen here too)
For data that needs to be persisted forever, either plugin-options, cache files or custom sql tables can be used
Admun wrote:
Thanks for the insight on insight, karma!
That's the exact purpose I put up these acticles, to share and learn more.
awesome!
Nice insight.