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 ?
A:
There are various ways to do it.
See:
http://raibledesigns.com/rd/entry/oscon%5F2008%5Fcaching%5Fand%5Fperformance
Daniel Alvarez Arribas
2009-09-04 23:11:57
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
2009-09-04 23:46:05
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
2010-05-19 19:57:29