Session-based object instantiation with memcached

Published: 08 March 2009

I can't help but ponder every so often the amount of objects that gets instantiated for a typical request when a framework-based application gets large and saturated. At runtime, a script sets up everything that it requires, allocating memory for variables and objects and all these gets torn down upon end of execution. There is no persistency beyond the notion of a session. And so a user goes about requesting for login.php and subsequently requests for say, MenuController.php in essence runs two disparate scripts without PHP bothering if they are from the same chap other than the fact that the session remains similar alongside any other information that might be stored in the session. This implies that an object instantiated upon login.php will no longer be present upon MenuController.php and needs to be instantiated again, that is unless it is stored in the session (and the code explicitly uses the object in session). So, there will be lots of object construction and destruction going on while the user of a PHP web app goes about her business dealing with the same app. Here's where object caching with memcached helps, but I thought another paradigm on top of it might be useful or feasible:

class SessionObjectSingleton
{
public static function getInstance($class)
{
if (!isset($_SESSION[$class])) {
$_SESSION[$class] = new $class;
}
return $_SESSION[$class];
}
}
So, everytime an object needs to be instantiated, we do this$newObj = SessionObjectFactory::getInstance("Some_class_name"); instead of $newObj = new Some_class_name;. Typical of a singleton but using a session as store, we get an object that persists along with the session that is specific to the session. Hence, the object can be user specific and still persist. Garbage collection is inherently managed when session_destroy() is called as usual. Furthermore, memcache can be used as the session handler, speeding up access to instantiated objects. (For more information on doing this, see phpslacker's session-clustering with memcache). Anyway, the objective of the whole shebang is to minimise resource use in a situation where objects are instantiated exhuberently. This paradigm has the utter inconvenience of having to instantiate object without the perennial new keyword, but heck other solutions seems to require expressive effort as well. It is also more useful for applications that needs to instantiate a lot of complex objects and maintain sessions that involve heavy state switching (e.g. back-end CMS-es). It is of course not relevant for applications that shouldn't be bothered with sessions in the first place. What do you think?