如下图所示建立工程:
代码如下:
- <?php
- /**
- * IndexController - The default controller class
- *
- * @author
- * @version
- */
- require_once 'Zend/Controller/Action.php';
- require_once 'Zend/Cache.php';
- require_once 'Zend/Registry.php';
- require_once 'Zend/Db.php';
- require_once 'Zend/Db/Table.php';;
- class IndexController extends Zend_Controller_Action
- {
- public function init()
- {
- $params = array ('host' => 'localhost',
- 'username' => 'root',
- 'password' => 'root',
- 'dbname' => 'mysql');
- $db = Zend_Db::factory('Pdo_Mysql', $params);
- Zend_Db_Table::setDefaultAdapter($db);
- Zend_Registry::set('db', $db);
- }
- public function indexAction()
- {
- $frontendOptions = array(
- 'lifeTime' => 7200, // 两小时的缓存生命期
- 'automatic_serialization' => true
- );
- $backendOptions = array(
- 'cache_dir' => 'C:/tmp/' // 放缓存文件的目录
- );
- // 取得一个Zend_Cache_Core 对象
- $cache = Zend_Cache::factory('Core',
- 'File',
- $frontendOptions,
- $backendOptions);
- if(!$result = $cache->load('myresult')) {
- // 缓存不命中;连接到数据库
- $dbAdapter = Zend_Registry::get('db');
- $result = $dbAdapter->query('SELECT * FROM user')->fetchAll();
- $cache->save($result, 'myresult');
- echo "This one is from database!<br/>";
- } else {
- // cache hit! shout so that we know
- echo "This one is from cache!<br/>";
- }
- print_r($result);
- }
- }