问题
I would like to create a set of persistent objects that load their state from the database and are then persisted in memory for Wordpress/PHP page loads to use as cached memory objects. I would imagine an interface for these objects to include:
- initialise() - load state from database and perform any other initialisation functions needed prior to servicing requests
- getter_foo() - a series of getter methods for PHP code to call for memory cached responses
- getter_bar() - a series of getter methods for PHP code to call for memory cached responses
- update() - called by time or event driven processes that ask the object to go back to the database and refresh its state
The two tricks I suspect are:
- Have the main PHP process alloc and hold the memory reference for these objects so that they remain pinned to memory across web transactions/requests without needing to reinitialise each time against the database
- Having a mechanism to allow the transactional processes to gain a pointer to this objects.
Are there any examples of solutions that do this? I've been programming for years but am very new to both Wordpress and PHP so maybe this is quite straight forward. Not sure. In any event, I do recognise that technical solutions like redis and memcached might achieve similar goals but in a less elegant and non-contextual way. That said, if there's no easy way to do this I'm happy to use the 80/20 rule. :^)
回答1:
It's not possible to store data in memory during 1 request, and then read it back from memory during another request using nothing but plain PHP. Sure the PHP process uses memory, but as soon as your request is finished, that part of the memory gets garbage collected. Which means that a second request cannot access that previous part of the memory again.
What you are hinting at, is called caching. Simply put, caching means that you save the output of an expensive transaction for later re-use, to save on the cost of that transaction. What you then use as a backend to store that output is up to you or what you have available. If you want to save it to the RAM, then you would need something like Memcached. You could also store it in regular file, but that is slower because of the hard drive being accessed.
来源:https://stackoverflow.com/questions/10583319/persistent-objects-in-wordpress-php