Is there a way to store a php object in memory to avoid reading disks and wirtes?

So, I have an object that reads a file from the gnugpg disk, it always creates the gnugpg key ring in the home directory.

I want to not load this object every time a php script is called from apache.

do you have php object in memory?

+5
source share
1 answer

If this is a small object that does not take up much memory and is serialized, you can simply save it in the session:

function    getSessionObject($objectName, $params){

    $sessionObjectSerialized = getSessionVariable($objectName, FALSE);

    if($sessionObjectSerialized == FALSE){
        $sessionObjectSerialized = constructSessionObject($objectName, $params);
        setSessionVariable($objectName, $sessionObjectSerialized);
    }

    $sessionObject = unserialize($sessionObjectSerialized);

    return $sessionObject;
}


function    constructSessionObject($objectName, $params = array()){

    switch($objectName){

        case('gnugpg_key_ring'):{
            $gnugpgKeyRing = getGNUPGKeyRing(); //do whatever you need to do to make the keyring.
            return serialize($countryScheme);
        }

        default:{
            throw new UnsupportedOperationException("Unknown object name objectName, cannot retrieve from session.");
            break;
        }
    }
}

//Call this before anything else
function initSession(){
    session_name('projectName');
    session_start();
}

function setSessionVariable($name, $value){
    $_SESSION['projectName'][$name] = $value;
}

function getSessionVariable($name, $default = FALSE){

    if(isset($_SESSION['projectName'])){
        if(isset($_SESSION['projectName'][$name])){
            $value = $_SESSION['projectName'][$name];
        }
    }
    return $default;
}

and then restore this object by calling

getSessionObject('gnugpg_key_ring');

, . , , , , , .

, , memcached, , .

+3

All Articles