Given a class with some really expensive code, I want to avoid running that code when re-defining an instance.
Best explained with some pseudo-code:
$foo = new Foo('bar'); print $foo->eat_cpu_and_database_resources(); #=> 3.14159 $foo->store_in_cache(); #Uses an existing Memcached and/or caching to store serialized. #new thread, such as a new HTTP request. Could be days later. $bar = new Foo('bar'); print $foo->eat_cpu_and_database_resources(); #=> 3.14159 The second $bar should re-initialize the earlier created instance $foo. Inside my actual class, I do several things on eat_cpu_and_database_resources(), which is named get_weighted_tags(): calculate a weighted tagcloud from values in $foo->tags. $foo->tags() was filled with expensive $foo->add_tag() calls. I would like to retrieve the prepared and filled instance from now on, from cache.
I have tried to simply fetch from (serialized) cache on __construct() and assign the retrieved instance to $this, which is not allowed in PHP:
function __construct ($id) { if ($cached = $this->cache_get($id)) { $this = $cached } else { #initialize normally } } Is this a proper way? Or should I treat every instance unique and instead apply caching in the eat_cpu_and_database_resources() method, instead of caching the entire instance?
Is there a built-in way in PHP to revive old instances (in a new thread)?
#new threadyou mean new request? Or do you just want to have the same instance during one request? Is theeat_cpumethod the expensive one or is it the actual object creation? Can you make the pseudecode more concrete please?store_in_cache()don't really matter, just the fact that it will serialize and persistent store the current instance.Foo_Factory::createwas the missing piece. Thanks.