如下圖所示建立工程:
代碼如下:
1.<?php
2.
3./**
4. * IndexController - The default controller class
5. *
6. * @author
7. * @version
8. */
9.
10.require_once 'Zend/Controller/Action.php';
11.require_once 'Zend/Cache.php';
12.require_once 'Zend/Registry.php';
13.require_once 'Zend/Db.php';
14.require_once 'Zend/Db/Table.php';;
15.
16.class IndexController extends Zend_Controller_Action
17.{
18. public function init()
19. {
20. $params = array ('host' => 'localhost',
21. 'username' => 'root',
22. 'password' => 'root',
23. 'dbname' => 'mysql');
24. $db = Zend_Db::factory('Pdo_Mysql', $params);
25. Zend_Db_Table::setDefaultAdapter($db);
26. Zend_Registry::set('db', $db);
27. }
28.
29. public function indexAction()
30. {
31. $frontendOptions = array(
32. 'lifeTime' => 7200, // 兩小時的緩存生命期
33. 'automatic_serialization' => true
34. );
35.
36. $backendOptions = array(
37. 'cache_dir' => 'C:/tmp/' // 放緩存文件的目錄
38. );
39.
40. // 取得一個Zend_Cache_Core 對象
41. $cache = Zend_Cache::factory('Core',
42. 'File',
43. $frontendOptions,
44. $backendOptions);
45. if(!$result = $cache->load('myresult')) {
46. // 緩存不命中;連接到數據庫
47. $dbAdapter = Zend_Registry::get('db');
48. $result = $dbAdapter->query('SELECT * FROM user')->fetchAll();
49. $cache->save($result, 'myresult');
50. echo "This one is from database!<br/>";
51. } else {
52. // cache hit! shout so that we know
53. echo "This one is from cache!<br/>";
54. }
55. print_r($result);
56. }
57.}