views:

59

answers:

2

In ASP.NET I can store both session and application state. Is the same true of PHP? I can't seem to find information on application state.

If not, what are best practices for shared state information? I need to build a somewhat complex data structure that all clients can utilize. It takes a while to build but is never edited after it's built.

thanks, Michael

+2  A: 

PHP doesn't have any equivalent to Application State. Your best option would be to maintain your data structure within APC or memcache (or WinCache on a Windows server).

Mark Baker
I have a question about create an application state variable using session. Could you please review it and help me clarify the problem? http://stackoverflow.com/questions/3760270/could-we-use-session-to-create-a-global-variable-for-all-client
coolkid
A: 

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.

ircmaxell