Reputation: 263
I am coding simple search engine (using vector model) and I have a big text file with indexes. In my application, I have to load the file and convert it to an array
At this moment, I create new instance of class in every page, which loads this file to the array.
Can I load this array only once (at the beginning) and then use the loaded one, which is written in RAM, I suppose?
Upvotes: 0
Views: 240
Reputation: 24116
Short answer; Yes!
There are several options you can use. PHP has a library called APC
You can do something like this...
<?php
$bar = 'BAR';
// store variable $bar in memory for 1 hour with key 'foo'
apc_store('foo', $bar, 3600);
var_dump(apc_fetch('foo'));
?>
Here's a proper use case example:
This automatically deals with expired cache and re-loads cache.
<?php
// Config?
define('CACHE_LIFESPAN', 3600); // 1 Hour
// Helper Function
function loadXYZData() {
$result = @apc_fetch(__FUNCTION__);
if (!$result) {
$result = array('a' => 'b', 'c' => 'd'); // dummy data
@apc_store(__FUNCTION__, $result, CACHE_LIFESPAN);
}
return $result;
}
// Usage - through out all your scripts
$myXYZData = loadXYZData();
var_dump($myXYZData);
?>
Here, the APC cache uses the function name as the cache key. So, you will be creating a function similar to the above per cacheable data in your application.
Above script's output is:
array (size=2)
'a' => string 'b' (length=1)
'c' => string 'd' (length=1)
Beyond APC, there are third party key value pair storage engine (in memory) like Memcached: http://www.php.net/manual/en/book.memcached.php
There are others, if you look around.
Upvotes: 1