user63898
user63898

Reputation: 30885

How to use global caching in php?

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 ?

Upvotes: 0

Views: 4793

Answers (2)

Gregoire
Gregoire

Reputation: 24832

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") ?>

Upvotes: 0

cletus
cletus

Reputation: 625007

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.

Upvotes: 3

Related Questions