Magento2 Extension installData script in modelFactory is necessary?

by Hims   Last Updated March 07, 2018 07:09 AM

I'm working on magento2 custom module. i have to install some data in my custom_table. so i am referencing below script.

i know the idea about $postFactory as describe here Magento2: How to add pre defined data (installData.php) for Custom Module .

I'm bit confused.
As mentioned below __construct function is calling postFactory:

Is it $postFactory necessary for inseting data??

If yes then my modulename & tabelname both are different so how can i do that ??

namespace Vendor\Modulename\Setup;

use Magento\Framework\Module\Setup\Migration;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
    private $_postFactory;

    public function __construct(\Vendor\Modulename\Model\PostFactory $postFactory)
        $this->_postFactory = $postFactory;

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        $data = [
            'title' => 'Hello world!',
            'content_heading' => 'Hello world!',
            'content' => 'logn description put here'



Answers 2

Yes it is necessary, it will decide in which table the data will be stored. Magento 2 is came up with the concept of factories.

Just go through this link When Should We Use a Repository and Factory in Magento 2?

March 07, 2018 06:57 AM

Magento2 Extension installData script in modelFactory is necessary?

I can say no.

We have another option: insert data directly to table. BUT using the factory is more convenient. For example, we can add more logic to check the data before inserting into the database. A model factory is for CRUD operations, not just for installing data.

We need to build Model, Resource Model, Collection to fully work with database.

Khoa TruongDinh
Khoa TruongDinh
March 07, 2018 07:00 AM

Related Questions

clean way of uninstalling extensions

Updated May 26, 2016 08:03 AM

Use plugin to modify content of catalog tab

Updated July 15, 2015 13:04 PM

Magento extension not showing up in back-end

Updated October 03, 2017 09:09 AM