Is it possible to cache only a specific part of a page in PHP, or the output of a specific section of code in the PHP script? It seems when I try to cache a particular page, it caches the whole page which is not want I want, some of the content in my page should be updated with every page load while others (such as a dropdown list with data from a database) only needs to be updated every hour or so.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
If you are talking about caching by the browser (and any proxies it might interact with), then no. Caching only takes place on complete HTTP resources (i.e. on a per URI basis).
Within your own application, you can cache data so you don't need to (for example) hit the database on every request. Memcached is a popular way to do this.
You could roll your own caching with ob_start(), ob_end_flush() and similar functions. Gather the desired output, dump it into some file or database, and read later if conditions are the same. I usually build md5 sum of the state and restore it later.
It depends on both what caching and view technologies are you using. Generally speaking yes, you can do something like this:
taken from Zend_Cache documentation.
Otherwise in your example you can always make a function which returns the dropdown list and implement the cache mechanism inside that function. In this way your page is not even aware of caching.
Zend_Cache
I would probably use Zend Frameworks
Zend_Cache
library for this.You can just use this component without needing to use the entire framework.
Step over to Zend Framework Download Page and grab the latest.
After you have downloaded the core files, you will need to include Zend_Cache in your project. Zend_Cache docs.
Have you decided how you want to cache your data? Are you using a file system? Or are you memcache? Once you know which you are going to use, you need to use a specific Zend_Cache backend.
Zend_Cache Backends / Zend_Cache Frontends
Backend documentation: Zend_Cache Backends Frontend documentation: Zend_Cache Frontends
So you would do something like this...
This would create a cache which makes use of the
Zend_Cache_Frontend_Output
caching mechanisms.To use
Zend_Cache_Frontend_Output
which is want you want, it would be simple. Instead of the core you would useoutput
. The options which you pass are identical. Then to use it you would:Zend_Cache_Frontend_Output - Usage
Useful Blog: http://perevodik.net/en/posts/14/
Sorry this question took longer to write than expected and lots of answers have been written I see!