SlideShare a Scribd company logo
Magento IndexersIvan ChepurnyiMagento Trainer / Lead Developer
AgendaMagento Developers MeetupOverview of Indexes FunctionalityCreation of own indexes
Let Imagine…Magento Developers Meetup… that Magento doesn’t have indexes:The prices in product list are calculated on the fly depending on catalog rules, tier prices for customer groupsStock availability for configurable and bundle products can be calculated only after loading the product collectionLayered navigation data is build in real-time for product attributes informationAnchor categories recursively collects subcategories for filtering product list
It’s all about performance…Magento Developers MeetupThe main goal is minimizing amount of operations to display products to a customer
DefinitionsMagento Developers MeetupIndexed DataAggregated data for entity representation on the frontend lists.Indexer	Generates index data on event or manual by process.Index EventThe moment when entity or related to it information is changed and that affects its index data.Index ProcessWrapper for indexer and contains information about its mode and statusMain Controller	Forwards events to Index Process
Index WorkflowMagento Developers MeetupEventMain ControllerEventEventsProcessManualInvokeIndexerIndexed Data
Event TypesMagento Developers MeetupSave	When indexed entity or related to it information was changedDeleteWhen indexed entity or related to it one was deletedMass UpdateWhen batch of entities was updated. (Update Attributes on Product Grid)
Observed Entities Magento Developers MeetupIndexed EntitiesProductProduct InventoryCategoryTagEntities ScopeCustomer GroupWebsiteStore GroupStore View
Index ProcessMagento Developers MeetupAvailable StatusesPending	Indicates that indexer is up to dateRunning	Index currently in process of full rebuilding index data.Require ReindexStatus for notifying admin user, that index is not up to date and should be rebuild.
Index ProcessMagento Developers MeetupIndexing ModesReal-timeManualUpdate Index DataEventEventRequire Reindex
Indexer Flow Magento Developers MeetupMatch EventMain ControllerIndex ProcessRegister Event DataReindex Data
Mage_Index ModuleMagento Developers MeetupMain ControllerMage_Index_Model_IndexerProcessMage_Index_Model_ProcessIndexer BaseMage_Index_Model_Indexer_Abstract
Index ModuleIndexers ModularityMagento Developers MeetupMage_Index_Model_Indexer_AbstractCatalog ModuleMage_Catalog_Model_Product_Indexer_EavMage_Catalog_Model_Product_Indexer_FlatMage_Catalog_Model_Product_Indexer_PriceInventory ModuleMage_CatalogIndex_Model_Indexer_Stock…
ModelMage_Index_Model_Indexer_AbstractIndexer StructureMagento Developers MeetupResource ModelMage_Index_Model_Mysql4_AbstractMatches event data and runs appropriate method in resource model for re-indexingWorks directly with database for generation of the indexed data. Usually all the data operated via MySQL queries.
What can you use?Magento Developers MeetupMage_Index_Model_IndexergetProcessByCode($indexerCode)getProcessCollection()processEntityAction($entity, $entityType, $eventType)Mage_Index_Model_ProcessreindexAll()reindexEverything()setMode($mode)
What you shouldn’t do…Magento Developers MeetupInvoke reindexAll method from index model/resource model, because it is better to let admin user know when the index was rebuild.Process entity events directly with indexer, instead of passing data through the main controller. You never know which index may depend on this event.
Creating own indexerMagento Developers MeetupDefining indexer in configurationDesigning index data tableImplementing model Implementing resource modelApplying index on the frontend
Featured ProductsMagento Developers MeetupThere is easier way to create featured products functionality, but it is a simple example on what should be done for creation own indexer.
Defining index in configurationMagento Developers Meetup<config><!-- …. module configurtaions -->   <global>   <!-- …. module configurtaions -->        <index><indexer>                <featured_products>                    <model>your_module/indexer_featured</model>                 </featured_products>            </indexer>        </index>    </global></config>etc/config.xmlIndexer Code Indexer Model
Designing index data tableMagento Developers MeetupAdding new attribute to catalog product entity called is_featuredCreating table that will contain product ids of products that are marked as featured products.
Designing index data tableMagento Developers Meetup$this->addAttribute('catalog_product', 'is_featured', array(    'type' => 'int',    'label' => 'Is featured',    'input' => 'select',    'source' => 'eav/entity_attribute_source_boolean',    'user_defined' => false,    'required' => false));Setup ScriptAttribute Code Yes/No Dropdown
Designing index data tableMagento Developers Meetup$table = new Varien_Db_Ddl_Table();$table->setName($this->getTable(‘module/featured'));$table->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11, array(    'unsigned' => true,    'nullable' => false,    'primary' => true));$this->getConnection()->createTable($table);Setup ScriptTable AliasTable Column
Designing index data tableMagento Developers Meetup$table = new Varien_Db_Ddl_Table();$table->setName($this->getTable(‘module/featured'));$table->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11, array(    'unsigned' => true,    'nullable' => false,    'primary' => true));$this->getConnection()->createTable($table);Setup ScriptTable AliasTable Column
Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{   protected $_matchedEntities = array(Mage_Catalog_Model_Product::ENTITY => array(Mage_Index_Model_Event::TYPE_SAVE, Mage_Index_Model_Event::TYPE_MASS_ACTION        ));}Defining Matching EventsEntity TypeEvent TypeEvent Types
Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{// … other codeprotected function _construct()    {        $this->_init(‘your_module/indexer_featured');    }}Defining Indexer Resource ModelResource model
Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{  // … other codepublic function getName()    {        return Mage::helper(‘your_module')->__('Featured Product');    }    public function getDescription()    {        return Mage::helper(‘‘your_module')->__('Indexes something');}}Defining Indexer InformationIndexer Name in the adminIndexer Description in the admin
Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{  // … other codeprotected function _registerEvent(Mage_Index_Model_Event $event)    {        /* @var $entity Mage_Catalog_Model_Product */        $entity = $event->getDataObject();        if ($entity->dataHasChangedFor('is_featured')) {            $event->setData('product_id', $entity->getId());        } elseif ($entity->getAttributesData()) {            $attributeData = $entity->getAttributesData();            if (isset($attributeData['is_featured'])) {                $event->setData('product_ids', $entity->getProductIds());            }}}}Register Event for ProcessingProduct Save RegisteringMass Action Registering
Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{  // … other code    protected function _processEvent(Mage_Index_Model_Event $event)    {        if ($event->getData('product_id') || $event->getData('product_ids')) {            $this->callEventHandler($event);        }}}Processing EventCalling processor in resource modelEntity TypeEvent TypecatalogProductSave($event)catalogProductMassAction($event)
Implementing Resource ModelMagento Developers Meetupclass Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract{   protected function _construct()    {        $this->_setResource(‘your_module');   }}Define resource connectionYour module resource prefix
Implementing Resource ModelMagento Developers Meetupclass Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract{    // … other code    protected function _reindexEntity($productId = null)    {        $select = $this->_getReadAdapter()->select();        /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */        $attribute = Mage::getSingleton('eav/config')                                   ->getAttribute('catalog_product', 'is_featured');        $select->from($attribute->getBackendTable(), 'entity_id')            ->where('value = ?', 1)            ->where('attribute_id = ?', $attribute->getId());Indexing MethodRetrieving only featured product ids
Implementing Resource ModelMagento Developers Meetupif ($productId !== null) {            if (!is_array($productId)) {                $productId = array($productId);            }            $select->where('entity_id IN(?)', $productId);            $this->_getWriteAdapter()->delete(                $this->getTable(‘your_module/featured'),                array(                    'product_id IN(?)' => $productId                )            );        } else {            $this->_getWriteAdapter()->truncate($this->getTable(‘your_module/featured'));        }Indexing MethodIf it is partial re-index, then delete only related indexed dataOtherwise clear all indexed data
Implementing Resource ModelMagento Developers Meetup$sqlStatement = $select->insertIgnoreFromSelect(            $this->getTable(‘your_module/featured'),            array('product_id')        );        $this->_getWriteAdapter()->query($sqlStatement);    }}Fulfill index data from select we created beforeIndexing Method
Implementing Resource ModelMagento Developers Meetupclass Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract{    // … other code    public function reindexAll()    {        $this->_reindexEntity();    }}Handling EventsFull index re-build
Implementing Resource ModelMagento Developers Meetupclass Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract{    // … other codepublic function catalogProductSave($event)    {        $this->_reindexEntity($event->getData('product_id'));    }public function catalogProductMassAction($event)    {        $this->_reindexEntity($event->getData('product_ids'));    }}Reindexing EventsSingle Save Product EventMass Save Product Event
Applying Index for the frontendMagento Developers MeetupObserving and event catalog_product_collection_apply_limitations_afterJoining index table to product collection selectCreate sub-select filter for collection
Liked it?Magento Developers MeetupCheckout our advanced training programs:http://www.ecomdev.org/magento-development-training-programs/advancedFollow our blog posts:http://www.ecomdev.org/blog
Questions?

More Related Content

What's hot (7)

PPTX
Ch12 Spring 起步走
Justin Lin
 
PPTX
Magento2.3 API Functional Testing
Vishwas Bhatnagar
 
PPTX
Maven
feng lee
 
PDF
vite-en.pdf
ssuser65180a
 
PPTX
Grails transactions
Husain Dalal
 
PDF
Java spring framework
Rajiv Gupta
 
PPTX
Firebase
Shady Selim
 
Ch12 Spring 起步走
Justin Lin
 
Magento2.3 API Functional Testing
Vishwas Bhatnagar
 
Maven
feng lee
 
vite-en.pdf
ssuser65180a
 
Grails transactions
Husain Dalal
 
Java spring framework
Rajiv Gupta
 
Firebase
Shady Selim
 

Viewers also liked (7)

PPTX
Mage Titans USA 2016 M2 deployment
Olga Kopylova
 
PPTX
Magento 2.0: Prepare yourself for a new way of module development
Ivan Chepurnyi
 
PPTX
Varnish Cache and its usage in the real world!
Ivan Chepurnyi
 
PPTX
Using of TDD practices for Magento
Ivan Chepurnyi
 
PPTX
Hidden Secrets of Magento Price Rules
Ivan Chepurnyi
 
PPTX
Making Magento flying like a rocket! (A set of valuable tips for developers)
Ivan Chepurnyi
 
PDF
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Ivan Chepurnyi
 
Mage Titans USA 2016 M2 deployment
Olga Kopylova
 
Magento 2.0: Prepare yourself for a new way of module development
Ivan Chepurnyi
 
Varnish Cache and its usage in the real world!
Ivan Chepurnyi
 
Using of TDD practices for Magento
Ivan Chepurnyi
 
Hidden Secrets of Magento Price Rules
Ivan Chepurnyi
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Ivan Chepurnyi
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Ivan Chepurnyi
 
Ad

Similar to Magento Indexes (20)

PPTX
Code Generation in Magento 2
Sergii Shymko
 
ODP
Edmonds Commerce Magento Presentation
Edmonds Commerce
 
PPTX
Magento 2 Database Tables, Schema, Main tables for main features of Magento 2...
gideonvbabu
 
PDF
Magento2dbschema1 180607144053
CHANDAN RAI
 
PPTX
Fixing Magento Core for Better Performance - Ivan Chepurnyi
Meet Magento Spain
 
PPTX
Igor Miniailo - Magento 2 API Design Best Practices
Atwix
 
PDF
How to import 1 million SKUs in under 10 minutes
Ivan Chepurnyi
 
PDF
Introduction to Magento Optimization
Fabio Daniele
 
PDF
Utilization of zend an ultimate alternate for intense data processing
Career at Elsner
 
PDF
Magento 2.1 ee content staging
Anton Kaplya
 
PDF
Alex Ursa: ERP Integrations with Magento: How to do it fast, good and affordable
Meet Magento Poland
 
PPTX
Optimizing Magento by Preloading Data
Ivan Chepurnyi
 
PDF
Magento Attributes - Fresh View
Alex Gotgelf
 
PPTX
Valeriy Nayda - Best Practices in Magento 2. Based on Multi Source Inventory ...
Atwix
 
PPTX
Magento Dependency Injection
Anton Kril
 
PDF
Vinai Kopp - How i develop M2 modules
Meet Magento Italy
 
PDF
Giuliana Benedetti - Can Magento handle 1M products?
Meet Magento Italy
 
PPTX
API design best practices
Igor Miniailo
 
PPTX
EAV Sytem- Magento EAV Model
Khoa Truong Dinh
 
PDF
Magento Product Types Demystified
AOE
 
Code Generation in Magento 2
Sergii Shymko
 
Edmonds Commerce Magento Presentation
Edmonds Commerce
 
Magento 2 Database Tables, Schema, Main tables for main features of Magento 2...
gideonvbabu
 
Magento2dbschema1 180607144053
CHANDAN RAI
 
Fixing Magento Core for Better Performance - Ivan Chepurnyi
Meet Magento Spain
 
Igor Miniailo - Magento 2 API Design Best Practices
Atwix
 
How to import 1 million SKUs in under 10 minutes
Ivan Chepurnyi
 
Introduction to Magento Optimization
Fabio Daniele
 
Utilization of zend an ultimate alternate for intense data processing
Career at Elsner
 
Magento 2.1 ee content staging
Anton Kaplya
 
Alex Ursa: ERP Integrations with Magento: How to do it fast, good and affordable
Meet Magento Poland
 
Optimizing Magento by Preloading Data
Ivan Chepurnyi
 
Magento Attributes - Fresh View
Alex Gotgelf
 
Valeriy Nayda - Best Practices in Magento 2. Based on Multi Source Inventory ...
Atwix
 
Magento Dependency Injection
Anton Kril
 
Vinai Kopp - How i develop M2 modules
Meet Magento Italy
 
Giuliana Benedetti - Can Magento handle 1M products?
Meet Magento Italy
 
API design best practices
Igor Miniailo
 
EAV Sytem- Magento EAV Model
Khoa Truong Dinh
 
Magento Product Types Demystified
AOE
 
Ad

Recently uploaded (20)

PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 

Magento Indexes

  • 1. Magento IndexersIvan ChepurnyiMagento Trainer / Lead Developer
  • 2. AgendaMagento Developers MeetupOverview of Indexes FunctionalityCreation of own indexes
  • 3. Let Imagine…Magento Developers Meetup… that Magento doesn’t have indexes:The prices in product list are calculated on the fly depending on catalog rules, tier prices for customer groupsStock availability for configurable and bundle products can be calculated only after loading the product collectionLayered navigation data is build in real-time for product attributes informationAnchor categories recursively collects subcategories for filtering product list
  • 4. It’s all about performance…Magento Developers MeetupThe main goal is minimizing amount of operations to display products to a customer
  • 5. DefinitionsMagento Developers MeetupIndexed DataAggregated data for entity representation on the frontend lists.Indexer Generates index data on event or manual by process.Index EventThe moment when entity or related to it information is changed and that affects its index data.Index ProcessWrapper for indexer and contains information about its mode and statusMain Controller Forwards events to Index Process
  • 6. Index WorkflowMagento Developers MeetupEventMain ControllerEventEventsProcessManualInvokeIndexerIndexed Data
  • 7. Event TypesMagento Developers MeetupSave When indexed entity or related to it information was changedDeleteWhen indexed entity or related to it one was deletedMass UpdateWhen batch of entities was updated. (Update Attributes on Product Grid)
  • 8. Observed Entities Magento Developers MeetupIndexed EntitiesProductProduct InventoryCategoryTagEntities ScopeCustomer GroupWebsiteStore GroupStore View
  • 9. Index ProcessMagento Developers MeetupAvailable StatusesPending Indicates that indexer is up to dateRunning Index currently in process of full rebuilding index data.Require ReindexStatus for notifying admin user, that index is not up to date and should be rebuild.
  • 10. Index ProcessMagento Developers MeetupIndexing ModesReal-timeManualUpdate Index DataEventEventRequire Reindex
  • 11. Indexer Flow Magento Developers MeetupMatch EventMain ControllerIndex ProcessRegister Event DataReindex Data
  • 12. Mage_Index ModuleMagento Developers MeetupMain ControllerMage_Index_Model_IndexerProcessMage_Index_Model_ProcessIndexer BaseMage_Index_Model_Indexer_Abstract
  • 13. Index ModuleIndexers ModularityMagento Developers MeetupMage_Index_Model_Indexer_AbstractCatalog ModuleMage_Catalog_Model_Product_Indexer_EavMage_Catalog_Model_Product_Indexer_FlatMage_Catalog_Model_Product_Indexer_PriceInventory ModuleMage_CatalogIndex_Model_Indexer_Stock…
  • 14. ModelMage_Index_Model_Indexer_AbstractIndexer StructureMagento Developers MeetupResource ModelMage_Index_Model_Mysql4_AbstractMatches event data and runs appropriate method in resource model for re-indexingWorks directly with database for generation of the indexed data. Usually all the data operated via MySQL queries.
  • 15. What can you use?Magento Developers MeetupMage_Index_Model_IndexergetProcessByCode($indexerCode)getProcessCollection()processEntityAction($entity, $entityType, $eventType)Mage_Index_Model_ProcessreindexAll()reindexEverything()setMode($mode)
  • 16. What you shouldn’t do…Magento Developers MeetupInvoke reindexAll method from index model/resource model, because it is better to let admin user know when the index was rebuild.Process entity events directly with indexer, instead of passing data through the main controller. You never know which index may depend on this event.
  • 17. Creating own indexerMagento Developers MeetupDefining indexer in configurationDesigning index data tableImplementing model Implementing resource modelApplying index on the frontend
  • 18. Featured ProductsMagento Developers MeetupThere is easier way to create featured products functionality, but it is a simple example on what should be done for creation own indexer.
  • 19. Defining index in configurationMagento Developers Meetup<config><!-- …. module configurtaions --> <global> <!-- …. module configurtaions --> <index><indexer> <featured_products> <model>your_module/indexer_featured</model> </featured_products> </indexer> </index> </global></config>etc/config.xmlIndexer Code Indexer Model
  • 20. Designing index data tableMagento Developers MeetupAdding new attribute to catalog product entity called is_featuredCreating table that will contain product ids of products that are marked as featured products.
  • 21. Designing index data tableMagento Developers Meetup$this->addAttribute('catalog_product', 'is_featured', array( 'type' => 'int', 'label' => 'Is featured', 'input' => 'select', 'source' => 'eav/entity_attribute_source_boolean', 'user_defined' => false, 'required' => false));Setup ScriptAttribute Code Yes/No Dropdown
  • 22. Designing index data tableMagento Developers Meetup$table = new Varien_Db_Ddl_Table();$table->setName($this->getTable(‘module/featured'));$table->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11, array( 'unsigned' => true, 'nullable' => false, 'primary' => true));$this->getConnection()->createTable($table);Setup ScriptTable AliasTable Column
  • 23. Designing index data tableMagento Developers Meetup$table = new Varien_Db_Ddl_Table();$table->setName($this->getTable(‘module/featured'));$table->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11, array( 'unsigned' => true, 'nullable' => false, 'primary' => true));$this->getConnection()->createTable($table);Setup ScriptTable AliasTable Column
  • 24. Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{ protected $_matchedEntities = array(Mage_Catalog_Model_Product::ENTITY => array(Mage_Index_Model_Event::TYPE_SAVE, Mage_Index_Model_Event::TYPE_MASS_ACTION ));}Defining Matching EventsEntity TypeEvent TypeEvent Types
  • 25. Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{// … other codeprotected function _construct() { $this->_init(‘your_module/indexer_featured'); }}Defining Indexer Resource ModelResource model
  • 26. Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{ // … other codepublic function getName() { return Mage::helper(‘your_module')->__('Featured Product'); } public function getDescription() { return Mage::helper(‘‘your_module')->__('Indexes something');}}Defining Indexer InformationIndexer Name in the adminIndexer Description in the admin
  • 27. Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{ // … other codeprotected function _registerEvent(Mage_Index_Model_Event $event) { /* @var $entity Mage_Catalog_Model_Product */ $entity = $event->getDataObject(); if ($entity->dataHasChangedFor('is_featured')) { $event->setData('product_id', $entity->getId()); } elseif ($entity->getAttributesData()) { $attributeData = $entity->getAttributesData(); if (isset($attributeData['is_featured'])) { $event->setData('product_ids', $entity->getProductIds()); }}}}Register Event for ProcessingProduct Save RegisteringMass Action Registering
  • 28. Implementing ModelMagento Developers Meetupclass Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract{ // … other code protected function _processEvent(Mage_Index_Model_Event $event) { if ($event->getData('product_id') || $event->getData('product_ids')) { $this->callEventHandler($event); }}}Processing EventCalling processor in resource modelEntity TypeEvent TypecatalogProductSave($event)catalogProductMassAction($event)
  • 29. Implementing Resource ModelMagento Developers Meetupclass Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract{ protected function _construct() { $this->_setResource(‘your_module'); }}Define resource connectionYour module resource prefix
  • 30. Implementing Resource ModelMagento Developers Meetupclass Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract{ // … other code protected function _reindexEntity($productId = null) { $select = $this->_getReadAdapter()->select(); /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */ $attribute = Mage::getSingleton('eav/config') ->getAttribute('catalog_product', 'is_featured'); $select->from($attribute->getBackendTable(), 'entity_id') ->where('value = ?', 1) ->where('attribute_id = ?', $attribute->getId());Indexing MethodRetrieving only featured product ids
  • 31. Implementing Resource ModelMagento Developers Meetupif ($productId !== null) { if (!is_array($productId)) { $productId = array($productId); } $select->where('entity_id IN(?)', $productId); $this->_getWriteAdapter()->delete( $this->getTable(‘your_module/featured'), array( 'product_id IN(?)' => $productId ) ); } else { $this->_getWriteAdapter()->truncate($this->getTable(‘your_module/featured')); }Indexing MethodIf it is partial re-index, then delete only related indexed dataOtherwise clear all indexed data
  • 32. Implementing Resource ModelMagento Developers Meetup$sqlStatement = $select->insertIgnoreFromSelect( $this->getTable(‘your_module/featured'), array('product_id') ); $this->_getWriteAdapter()->query($sqlStatement); }}Fulfill index data from select we created beforeIndexing Method
  • 33. Implementing Resource ModelMagento Developers Meetupclass Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract{ // … other code public function reindexAll() { $this->_reindexEntity(); }}Handling EventsFull index re-build
  • 34. Implementing Resource ModelMagento Developers Meetupclass Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract{ // … other codepublic function catalogProductSave($event) { $this->_reindexEntity($event->getData('product_id')); }public function catalogProductMassAction($event) { $this->_reindexEntity($event->getData('product_ids')); }}Reindexing EventsSingle Save Product EventMass Save Product Event
  • 35. Applying Index for the frontendMagento Developers MeetupObserving and event catalog_product_collection_apply_limitations_afterJoining index table to product collection selectCreate sub-select filter for collection
  • 36. Liked it?Magento Developers MeetupCheckout our advanced training programs:http://www.ecomdev.org/magento-development-training-programs/advancedFollow our blog posts:http://www.ecomdev.org/blog