Search code examples
phpapachefile-iognupg

Is there a way to keep a php object in memory to avoid disk reads and wirtes?


So I have an object that reads a file from disk gnugpg it appears to always create a gnugpg key ring in a home directory.

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

is there away to have a php object stay in memory?


Solution

  • If it's a small object that doesn't take up much memory and is serializable you could just store 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 retrieve that object by calling

    getSessionObject('gnugpg_key_ring');
    

    However not all objects are always serializable e.g. if the object holds a file handle to an open file, that would need to have some extra code to close the file when the object is serialized and then re-open the file when the object was unserialized.

    If the object is large, then you would be better off using a proper caching tool like memcached to store the serialized object, rather than the session.