This is the Aggressione Web Development Studio Weblog, where we write about things you might want to read about ... and anything else that we happen to be interested in sharing. For more information on us and what we do,
visit our main site.
RSS feeds. / ADD to Google Reader

Transparent Object Storage in PHP 5
by evgeni on July 15th, 2010

Hey there !

If you are like me and do a lot of PHP OO sooner or later you are going to come to the need of something that transparently stores data between your objects. Something that is easy to use and access and is more or less transparent to your application.

So today I am going to show you with some code how to achieve that and what are the benefits of it. Of course like many more things there is always more than one way of doing it, but I will show you mine. Let’s get started with some code.

class myStorage {
 
    private static $oInstance;
 
    protected static $objectValues;
 
    private function __construct() {
 
        self::$objectValues = new ArrayObject( $array = array(), ArrayObject::ARRAY_AS_PROPS );
    }
 
    public static function instance() {
 
        if ( empty ( self::$oInstance ) ) {
 
            self::$oInstance = new self();
        }
 
        return self::$oInstance;
    }
 
    /**
     * Magic method
     *
     * @param string $sKey
     * @param mixed $sValue
     */
 
    public function __set( $sKey, $sValue ) {
 
        if( !self::$objectValues->offsetExists( $sKey ) ) {
 
            self::$objectValues->offsetSet( $sKey, $sValue );
        }
        else {
 
            if ( is_array( $sValue ) ) {
 
                self::$objectValues->offsetSet( $sKey, array_merge( self::$objectValues->offsetGet( $sKey ), $sValue ) );
 
            }
            else {
 
                self::$objectValues->append( $sValue );
            }
        }
    }
 
    /**
     * Magic method
     *
     * @param string $sKey
     * @return mixed
     */
 
    public function __get( $sKey ) {
 
        if ( self::$objectValues->offsetExists( $sKey ) ) {
 
            return self::$objectValues->offsetGet( $sKey );
        }
    }
 
}

In this particular case I am using ArrayObject as storage, though this can be achieved with simple stdClass or just plain array instance.
First things first – this must be a singleton instance so your stored variables don’t get erased every time you invoke the storage class. The rest is pretty straight forward, just set two magic methods ( setter and getter ) .

Usage

 /** get an instance **/
 $oStorage = myStorage::instance();
 
/** set var **/
 $oStorage->myVar = "test_my_var";
 
/** retrieve var **/
echo $oStorage->myVar;

Now if the storage class is application wide available you can see the benefits of this simple storage idea that acts more or less like a transparent registry mechanism.

Leave a Reply