Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache a collection in Magento?

Tags:

magento

I have a collection that takes significant time to load. What I would like is to cache it (APC, Memcache). It is not possible to cache the entire object (as it cannot be unserialized and it is over 1 MB). I'm thinking that caching the collection data ($col->getData() ) is the way to go, but I found no way to rebuild the object based on this array. Any clues?

like image 243
Paul Grigoruta Avatar asked Sep 20 '10 20:09

Paul Grigoruta


1 Answers

Collections already have some caching built in but they need a little prompting so put this in the constructor of a collection:

$cache = Mage::app()->getCacheInstance();
$prefix = "SomeUniqueValue";
$this->initCache($cache, $prefix, array(Mage_Catalog_Model_Product::CACHE_TAG));

Choose tags appropriate to the content of the collection so that it will be flushed automatically. This way builds an ID based on the query being executed, it is most useful when the collection is filtered, ordered or paged - it avoids a version conflict.

Generally this hardly gets used because when you retrieve data you almost always end up displaying it, probably as HTML, so it makes sense to cache the output instead. Block caching is widely used and better documented.

like image 109
clockworkgeek Avatar answered Oct 21 '22 06:10

clockworkgeek