While PHP doesn't have an inbuilt application state system, you can emulate one pretty easy if you don't write after it's built (you can emulate it if you need to write, but concurrency issues will make it a lot harder to do properly).
Basically, PHP provides a serialize
method to store objects in strings. You could then build a simple caching layer in a factory class to store the object on the filesystem:
class Factory {
public static function getFooObject() {
$signature = 'foo';
$obj = self::getStoredObject($signature);
if (!$obj) {
$obj = new Foo();
self::storeObject($signature, $object);
}
return $obj;
}
public static function getFooBarObject($arg1) {
$signature = 'foobar_'.md5(serialize($arg1));
$obj = self::getStoredObject($signature);
if (!$obj) {
$obj = new FooBar($arg1);
self::storeObject($signature, $object);
}
return $obj;
}
protected function getStoredObject($signature) {
$path = PATH_TO_CACHE . $signature;
if (file_exists($path)) {
$data = file_get_contents($path);
$obj = @unserialize($data);
return $obj; //Would return false on error, so we're ok
}
return false;
}
protected function storeObject($signature, $obj) {
$path = PATH_TO_CACHE . $signature;
file_put_contents($path, serialize($obj));
}
}
That's all there really is to it. If you wanted to get fancy you could implement a meta-data system and version your classes so that if you made a change to the underlying class it would implicitly flush the cached object and re-initialize it.