/   /   /  Magento 2 Concept : Model Resource DB and Collection (part3)

Note:

For more extensions and themes visit our store

Magento 2 Concept : Model Resource DB and Collection (part3)


This  course of series give you the ability for creating your own model resource and collection , ok let's imagine you want create a simple module for persist some data like brand infos for example .

you can download file of this course and code from github

1 – Create :

First we need create our table inside our database for that you need create the Setup folder ,The path complete of module is Ibnab/Brand , inside Setup folder create  file InstallSchema.php and fill with :

  1.  
  2. <?php
  3. namespace Ibnab\Brand\Setup;
  4. use Magento\Framework\Setup\InstallSchemaInterface;
  5. use Magento\Framework\Setup\ModuleContextInterface;
  6. use Magento\Framework\Setup\SchemaSetupInterface;
  7. /**
  8.  * @codeCoverageIgnore
  9.  */
  10. class InstallSchema implements InstallSchemaInterface {
  11.     /**
  12.      * {@inheritdoc}
  13.      */
  14.     public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) {
  15.         $installer = $setup;
  16.         $installer->startSetup();
  17.         $installer->getConnection()->dropTable($installer->getTable('ibnab_brand'));
  18.         $table = $installer->getConnection()->newTable(
  19.             $installer->getTable('ibnab_brand')
  20.         )->addColumn(
  21.             'brand_id',
  22.             \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
  23.             10,
  24.             ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
  25.             'Slider ID'
  26.         )->addColumn(
  27.             'name',
  28.             \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
  29.             255,
  30.             ['nullable' => false, 'default' => ''],
  31.             'Brand title'
  32.         )->addColumn(
  33.             'image',
  34.             \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
  35.             255,
  36.             ['nullable' => true],
  37.             'Brand image'
  38.         );
  39.         $installer->getConnection()->createTable($table);
  40.         $installer->endSetup();
  41.     }
  42. }
  43.  

Magento 2 use this class inside Setup for create all needed  schema when you try to complete the  installation of your module in first time with command in terminal: php bin/magento setup:upgrade
here we use resource for unit Setup inside framework magento2 it's give core_resource for write and read from db .
Here we used 2 cool function dropTable and newTable . The injected $setup object give you an adapter for using dropTable and newTable functions ( dropTable and newTable exist inside Magento\Framework\DB\Adapter\Pdo\Mysql).

Second we need create model The path complete of module is Ibnab/Brand , create the folder model and inside it create your model Brand.php ,  with content :

  1.  
  2. <?php
  3. namespace Ibnab\Brand\Model;
  4. class Brand extends \Magento\Framework\Model\AbstractModel
  5. {
  6.   protected function _construct()
  7.     {
  8.         $this->_init('Ibnab\Brand\Model\ResourceModel\Brand');
  9.     }
  10. }
  11.  

simple use case for more explain you need go to course Model Resource DB and Collection (part1) of this series

inside  Ibnab/Brand/Model/ResourceModel create Brand.php  (push):
  1.  
  2. <?php
  3. namespace Ibnab\Brand\Model\ResourceModel;
  4. class Brand extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
  5. {
  6.     protected function _construct()
  7.     {
  8.         $this->_init('ibnab_brand', 'brand_id');
  9.     }
  10. }
  11.  

simple use case for more explain you need go to course Model Resource DB and Collection (part1) of this series

and inside  Ibnab/Brand/Model/ResourceModel/Brand create Collection.php (push):
  1.  
  2. <?php
  3. namespace Ibnab\Brand\Model\ResourceModel\Brand;
  4. class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
  5. {
  6.     protected function _construct()
  7.     {
  8.         $this->_init('Ibnab\Brand\Model\Brand', 'Ibnab\Brand\Model\ResourceModel\Brand');
  9.     }
  10. }
  11.  

simple use case for more explain you need go to course Model Resource DB and Collection (part2) of this series

2 – Use :

Ok let's imagine you are create simple controller inside Ibnab/Brand/Controller/Index/Index.php
 (this controller is frontend type , for testing  you need create the inside Ibnab/Brand/etc/frontend/routes.xml see inside the attachment file with this coure  ) and the content is :

  1.  
  2. <?php
  3. namespace Ibnab\Brand\Controller\Index;
  4. class Index extends \Magento\Framework\App\Action\Action
  5. {
  6.     protected $_brandFactory;
  7.     public function __construct(
  8.         \Magento\Framework\App\Action\Context $context,
  9.         \Ibnab\Brand\Model\BrandFactory $brandFactory
  10.     ) {
  11.         $this->_brandFactory = $brandFactory;
  12.         parent::__construct($context);        
  13.     }
  14.     public function execute()
  15.     {
  16.         /***create and save**/
  17.         $brandModel = $this->_brandFactory->create();
  18.         $brandModel->setName('Ibnab');
  19.         //or $brandModel->setData('name','Ibnab');
  20.         $brandModel->setImage('logo.png');
  21.         //or $brandModel->setData('image','logo.png');
  22.         $brandModel->save();
  23.         var_dump($brandModel->getData());
  24.         echo "";
  25.         $collection = $brandModel->getCollection();
  26.         echo "total brand is : ".$collection->count()."";
  27.         foreach($collection as $brand):
  28.             echo $brand->getName()."<br/ >";
  29.             echo $brand->getImage()."<br/ >";
  30.         endforeach;
  31.         die();
  32.    }
  33. }
  34.  

 

use can inject your model in __construct of controller (action) , but not directly we use here technique of factory for building our object (we need obtain all dependency in life cycle of object),
ok inside main function (public function execute())  , we use function create of factory for getting model brand instance of  Ibnab\Brand\Model\Brand , we can use directly setters with name of field of using the setData method (with setName we ufing the technique of magic method that take more time for compilation) , and you can use getters or directly with popular function getData.

You can get instance of class  Ibnab\Brand\Model\ResourceModel\Brand\Collection with method $brandModel→getCollection(); (you can inject directly in __construct like model Ibnab\Brand\Model\ResourceModel\Brand\CollectionFactory and get the instance with function create ) , here we use method count and we using iterator for browse all brand every loop give you an instance type   Ibnab\Brand\Model\Brand , with values of current row .

Comments

Related Posts

make your store more efficient

Solving problems. With open source technology. Professional results. That’s what makes Ibnab your best choice

IBNAB is a company made of a group of professionals whose work is providing secure open source solutions. Our company strives for reaching magnificent results with each experience and provides professional open source solutions that cover every part of the business process.