Alaa
Alaa

Reputation: 4611

how to create shared object in memory using PHP?


I have a block in my website that shows the latest 20 items in a database table.
now I need to create an array or object to reside in memory and then to access it for all users who browse my website? Can I do it using PHP?

Thanks for your help

Upvotes: 1

Views: 2741

Answers (3)

Alaa
Alaa

Reputation: 4611


Thanks for your contributions.
i found a way to do it.
The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide framework for caching.
try this code and refresh the page or open it using different browsers

<?php 
if (apc_exists('test'))
     echo apc_fetch('test');
else{
   echo "Just Created ";
   apc_store("test",time(),6666);
   echo  apc_fetch('test');
}
?>

Upvotes: 1

Ankur
Ankur

Reputation: 111

PHP is stateless so it is not possible to easily to share the variable between the different session. You can do this by one trick. Create array of all these value, Now serialize the array $sharedObj = serialize ($originalArray) ; you can get Serialize variable of your $originalArray in $sharedObject Write the $sharedObject into a text file and you can read the text file and unserialize that data(which you are getting from the text file) and you can get the same array.

Please let me know if you still have problem.

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212422

Look at options like APC or memcache, or WinCache if you're on a Windows server. These all provide options to cache data/objects.

If this is to show the latest items on a database, you'd need to update it every time something is added to that database, otherwise it won't be consistent with the database

Upvotes: 2

Related Questions