Zend cache

From EKiniWiki

Jump to: navigation, search

Here is a sample code to cache the SQL query.

...
This is a part of the Action
...
        //for the cache
        $frontendOptions = array();
        $frontendOptions['lifetime'] = 7200;
        $frontendOptions['automatic_serialization'] = true;
        
        $backendOptions = array();
        $backendOptions['cache_dir'] = Zend_Registry::get('cache_dir');
        
        // getting a Zend_Cache_Core object
        $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
        
        // see if a cache already exists:
        if(!$result_pop_songs = $cache->load('pop_songs')) {
            //get most popular songs
            $dbAdapter = Zend_Registry::get('dbAdapter');
            $sql = 'SELECT
                    s.song_title, 
                    s.song_slug, 
                    s.song_counter,
                    at.artist_slug
                    FROM songs_table s
                    LEFT JOIN album_table al ON s.album_id=al.album_id
                    LEFT JOIN artist_table at ON al.artist_id=at.artist_id
                    WHERE s.song_counter>0 ORDER BY s.song_counter DESC LIMIT 10';
            $this->view->pop_songs = $dbAdapter->fetchAll($sql);
            $cache->save($this->view->pop_songs, 'pop_songs');
        } else {
            // cache hit! shout so that we know
            //echo "This one is from cache!\n\n";
            $this->view->pop_songs = $result_pop_songs;
        }

In this example, my songs_table contains about 150K and the artist table contains more than 10K rows, so it would make sense not to execute the SQL query again. Especially on the frontpage.

Personal tools
Bookmarks