I have a function that is slow because of MySQL queries.
The function will return the same result as long as certain MySQL tables remain unchanged.
What is the simplest way to “memoize” such a function in PHP/MySQL?
edit:
What I would like to see is:
- Something like a table hash/last modified date for a table from MqSQL.
- Something from PHP side being clever enough to figure out what tables a function may access and cache/retrieve the results if approriate.
You are most likely looking for caching methods of data.
Here are a few methods that may be of interest:
memcached/APC
If you have access to a host that supports this, go for it. This is the single, fastest way to store and retrieve data today.
Reference: http://www.php.net/manual/en/book.memcached.php
File caching
You can use the file library in PHP to save data to a file and retrieve it whenever required. This may be useful for Javascript data as well as you can dynamically load the .js file on-demand.
Reference: http://www.php.net/manual/en/ref.filesystem.php
SQL caching
You can also store your results on a separate table (assuming you are using a complex operation that is expensive and not pulling it off a single table already) for easy read/write access.
Reference: http://www.php.net/manual/en/ref.pdo-mysql.php
It may be in your interest to look at
cronjobsin order to delete your cached data over time as well (in order to save space or update the cache).Reference: http://en.wikipedia.org/wiki/Cron
Enjoy and good luck!