Snippet. PHP. Registering Key-Value Pairs in a Pool in OOP Manner

This convenient PHP snippet shows use a pool to store arrays with data and avoid repetitive and time consuming computations.

The class Pool keeps registry of the submitted data as key-value pairs. This allows to check, if a key-value pair is already registered and execute or not an action based on the result. For instance, by using this small utility class for optimization the repetitive queries to database may be eliminated, thus reducing total number of queries by as much as 50%, reducing server load and reducing web page loading time considerably (almost in half).

//============================= START OF CLASS ==============================//
// CLASS: Pool                                                               //
//===========================================================================//
class Pool {
    private static $_store = array();

    private function __construct(){}

    public static function set($key,$value) {
        if(isset(self::$_store[$key]) === false)self::$_store[$key] = $value;
    }

    public static function get($key) {
        if(isset(self::$_store[$key]) === false) throw new RuntimeException('Key '.$key.' DOES NOT exist in Pool');
        return self::$_store[$key];
    }

    public static function exists($key) {
        if(isset(self::$_store[$key]) === true) return true;
        return false;
    }

    public static function update($key,$data) {
        if(isset(self::$_store[$key]) === false) throw new RuntimeException('Key '.$key.' DOES NOT exist in Pool');
        self::$_store[$key] = array_merge(self::$_store[$key],$data);
    }
}
//===========================================================================//
// CLASS: Pool                                                               //
//============================== END OF CLASS ===============================//

Example usage


// Adding 100 arrays
for ($i=0; $i<100; $i++) {
    Pool::set('Key'.$i, array('ID'=>$i, 'CATEGORY_NAME'=>'Name'.$i));
}

// Updating data at Key10
if (Pool::exists('Key10') == true) {
    Pool::update('Key10',array('CATEGORY_NAME'=>'New name'));
}

// Retrieving data at Key10
if (Pool::exists('Key10') {
    $category10 = Pool::get('Key10');
    var_dump($category10);
}

Updated on: 18 Apr 2024