仅缓存PHP页面的一部分 [英] Cache only part of a page in PHP
问题描述
是否可以仅在PHP中缓存页面的特定部分,或在PHP脚本中缓存特定代码部分的输出?看来,当我尝试缓存特定页面时,它会缓存整个我不想要的页面,页面中的某些内容应随每次页面加载而更新,而其他内容(例如具有数据库数据的下拉列表) )仅需要每小时左右进行更新。
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.
推荐答案
Zend_Cache
我可能会为此使用Zend Frameworks Zend_Cache
库。
您可以使用此组件而无需使用整个框架。
You can just use this component without needing to use the entire framework.
转到 Zend Framework下载页面并获取最新版本。
下载核心文件后,您需要在项目中包含Zend_Cache。
Zend_Cache 文档。
After you have downloaded the core files, you will need to include Zend_Cache in your project. Zend_Cache docs.
您是否已决定要如何缓存数据?您正在使用文件系统吗?还是您是Memcache?一旦知道要使用的对象,就需要使用特定的Zend_Cache后端。
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后端
前端文档: Zend_Cache前端
做这样的事情...
<?php
// configure caching backend strategy
$backend = new Zend_Cache_Backend_Memcached(
array(
'servers' => array( array(
'host' => '127.0.0.1',
'port' => '11211'
) ),
'compression' => true
) );
// configure caching frontend strategy
$frontend = new Zend_Cache_Frontend_Output(
array(
'caching' => true,
'cache_id_prefix' => 'myApp',
'write_control' => true,
'automatic_serialization' => true,
'ignore_user_abort' => true
) );
// build a caching object
$cache = Zend_Cache::factory( $frontend, $backend );
这将创建一个使用 Zend_Cache_Frontend_Output $ c的缓存$ c>缓存机制。
This would create a cache which makes use of the Zend_Cache_Frontend_Output
caching mechanisms.
要使用想要的 Zend_Cache_Frontend_Output
,它将为简单。您可以使用 output
代替核心。您传递的选项是相同的。然后要使用它,您将:
To use Zend_Cache_Frontend_Output
which is want you want, it would be simple. Instead of the core you would use output
. The options which you pass are identical. Then to use it you would:
// if it is a cache miss, output buffering is triggered
if (!($cache->start('mypage'))) {
// output everything as usual
echo 'Hello world! ';
echo 'This is cached ('.time().') ';
$cache->end(); // output buffering ends
}
echo 'This is never cached ('.time().').';
有用的博客: http://perevodik.net/en/posts/14/
对不起,这个问题写的时间比预期的长我看到了很多答案!
Sorry this question took longer to write than expected and lots of answers have been written I see!
这篇关于仅缓存PHP页面的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!