Magento 2: Basic concepts of models, resource models, and collections

There are four types of classes related to loading and storing data in Magento.

  • Models: stored directly in the module's Model/ directory: these are classes with getters and setters to store data. An instantiated class would represent one row in the database. This model is initialized with a reference to the Resource Model. Example: \Magento\Cms\Model\Page.
  • Resource models: stored in the module's Model/ResourceModel/ directory, these classes are responsible for saving and loading data. These classes almost always inherit
    \Magento\Framework\Model\ResourceModel\Db\AbstractDb
    
    The primary methods in this class are aptly named: load, save and delete. Please see the examples in the sample project for how to configure this class. However, the resource model is the place to put any custom selects (using the Magento ORM, and NOT writing direct SQL).
  • Collections: stored in the module's Model/ResourceModel/[Model Name]/Collection.php file, this class loads multiple models. This class is initialized with a reference to the Model and Resource Model. If you wish to utilize a CMS Page collection in one of your classes, you must use a Factory (
    Magento\Cms\Model\ResourceModel\Page\CollectionFactory
    
    ) and instantiate that collection ($this->collectionFactory->create()) instead of injecting the collection class itself.

Ready to elevate your e-commerce business?

Discuss your business objectives with us. Get in touch today to explore ways we can assist in reaching them.

Copyright © 2021-2024 ArmMage LLC. All rights reserved.