Zend Framework Tutorial
By Lyndon Baptiste2008-08-13
Take a look at the following action which I want you to paste starting from line 66 of the IndexController:
public function cachelistAction() {
$db = Zend_Registry::get('db');
$cache = Zend_Registry::get('cache');
require_once 'models/User.php';
$user = new User();
$userInfo = $user->info();
$tblUser = $userInfo['name'];
if (!$result = $cache->load('userlist')) {
$select = $db->select();
$select->from($tblUser);
$result = $db->fetchAll($select);
$cache->save($result, 'userlist');
}
$this->view->userList = $result;
$this->render();
}
On line 67 and 68 we reclaim our global variables which we registered with Zend_Registry. To return the values simply specify the key as a parameter to the get method. By now line 70 to 73 should be familiar to us. According to the Zend Framework documentation
"There are three key concepts in Zend_Cache. One is the unique indentifier (a string) that is used to identify cache records. The second one is the 'lifetime' directive as seen in the examples; it defines for how long the cached resource is considered 'fresh'. The third key concept is conditional execution so that parts of your code can be skipped entirely, boosting performance."
In our case on line 75 this is the "userlist" which we attempt to load. If the cache does not have such a record, the variable $result will be null and the code within the if statement executed. The lifetime directive was already specified on line 31 of index.php. In our example a registered user list will not be fresh after every registration so a lifespan of 2 hours may be unrealistic. This is merely for the purpose of demonstration. Therefore line 76 to 79 will include code that can get and cache the user list. Another feature of Zend_Db is demonstrated. The database object can be used to create a select object specific to the adapter specified in the beginning. This select object is ideal when forming SQL statements based on logic for example joining to or ordering tables based on some sort parameter specified in a get request. Notice that on line 77 the literal name of the table is not used but rather the info derived from the user class. Through a call to fetchAll which can take a sql string or select object, the results are returned and then cached using the save method. At this point the key is specified and data. Remember we configured the cache to automatically serialise our results so it's okay even though an array of results will be returned. Results are also automatically unserialized. You can follow the code in list.phtml and attempt to write a view script for cachelist.phtml. It's very easy!
Tutorial pages:
|
|
|||||||||
You might also want to check these out:
|
Link to This Tutorial Page!

