tags:

views:

328

answers:

3

ello all im new to php and server scripting ( coming from the java/cpp background ) my question is , if i like to be able to build some kind of single tone cache that will hold me data in memory in all the web application life , something that when i start the web server it will start main cache that will server the web application not inside sessions static cache like singletone map in c++/java that that leaves all the time what are my options ?

+2  A: 

For this in PHP you need APC, which comes pretty much as standard with PHP these days (and will be standard as of PHP 6)--all you have to do is enable it in the config--or memcached, particularly if you've got some sort of clustered solution.

cletus
A: 

There are various ways to do it.

See:

http://raibledesigns.com/rd/entry/oscon%5F2008%5Fcaching%5Fand%5Fperformance

Daniel Alvarez Arribas
While APC is most often used as an opcode cache it CAN do general purpose caching of data, hence the purpose of apc_add/apc_fetch, etc. It uses shared memory as a cache store. But given the choice, I prefer memcached.
Cody Caughlan
A: 
function resetCache(){
    restoreCacheSession();
    session_unset();
    restoreTrueSession();
}

function restoreCacheSession(){

    $sessionId = session_id();
    if(strlen($sessionId))  {
        $origSetting = ini_get('session.use_cookies');
        session_write_close();
    }

    session_id('cache');
    ini_set('session.use_cookies', false);
    session_start();

    if($sessionId)
    {
        $_SESSION["_trueSessionId"] = $sessionId;
        $_SESSION["_trueSessionSettings"] = $origSetting;
    }
}

function restoreTrueSession(){
    if(isset($_SESSION["_trueSessionId"])){
        $sessionId = $_SESSION["_trueSessionId"];
        $origSetting = $_SESSION["_trueSessionId"];
    }

    session_write_close();

    if(isset($sessionId)) { 
        ini_set('session.use_cookies', $origSetting);
        session_id($sessionId);
        session_start();
    } 
    elseif(isset($_COOKIE['phpSESSID'])){ 
        session_id($_COOKIE['phpSESSID']);
        session_start();
    } 
    else { 
        session_start();
        session_unset();
        session_regenerate_id();
    }   
}

function cache($var, $value = null){
    restoreCacheSession();
    if(!isset($value)){
        if(isset($_SESSION[$var])){
            $result = $_SESSION[$var];
        }

        restoreTrueSession();
        return isset($result)?$result:null;
    }

    $_SESSION[$var] = $value;

    restoreTrueSession();
}

To set a variable in the cache you only have to <?php cache("yourvarname",yourvarvalue) ?> To get the value of a variable in the cache: <?php cache("yourvarname") ?> To reset the cache <?php resetCache("yourvarname") ?>

Gregoire