Create a model class, resource, and data collection

Magento uses "thin" models. For this, two models are created:

  1. The usual model for implementing business logic,
  2. Resource model - to interact with the database.

And so, we need to create two models + resource class. The resource class is used to output grid data.

Create a model class

Create a folder:


Adding a file:


Adding the code:

class My_Articles_Model_Articles extends Mage_Core_Model_Abstract { public function _construct() { parent::_construct(); /** * Initializing the model. In the configuration file (see below) * Tag <myarticles> / File Articles.php */ $this->_init("myarticles/articles"); } }
Note that here _construct () is correct, not __construct ()

Adding a Resource Model

Here we implement the removal of the image after the deletion of the record, as well as the output functionality of the path to the picture.

Create a folder:


Create a file:


Adding the code:

class My_Articles_Model_Resource_Articles extends Mage_Core_Model_Mysql4_Abstract { public function _construct() { /* Initialize the resource model. In the configuration file (see below) Tag <myarticles> / tag <table_myarticles> id - field name with Primary Key */ $this->_init("myarticles/table_myarticles", "id"); }
/** * Function is called after data is deleted * Here we delete the picture file * @return Mage_Core_Model_Resource_Db_Abstract */ protected function _afterDelete() { $helper = Mage::helper('myarticles'); @unlink($helper->getImagePath($this->getId())); return parent::_afterDelete(); }
/** * The function returns the path to the image * We will use our helper for this * @return null */ public function getImageUrl() { $helper = Mage::helper('myarticles'); if ($this->getId() && file_exists($helper->getImagePath($this->getId()))) { return $helper->getImageUrl($this->getId()); } return null; } }

Adding to the configuration file


We need to add parameters (see comments)

  1. Code for models
  2. The code for the model resources
<?xml version="1.0" ?>
   <!-- Code for controller -->
   <!-- Code for models -->
            <!-- We created a class My_Articles_Model_Articles, in this parameter, we only specify the path to the file My_Articles_Model without the filename Articles -->
        <!-- The code for the model resources -->
       <!-- Code for adding tables to the database -->

Creating a model of collections

Resources are used to output a list of data from the model. Resources are used in data grid

Create a folder:


Create a file:


Adding the code:

class My_Articles_Model_Resource_Articles_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract { public function _construct() { parent::_construct(); /** * Initialize the model collection. In the configuration file * Tag <myarticles> / File Articles.php */ $this->_init('myarticles/articles'); } }

Article Source: https://кодер.укр/записи/magento-1-создание-модуля-часть-5-модели.