Magento 2 Custom Commands – How to Perform CRUD Operations

crudmagento2

How to create custom commands to perform crud operations in Magento 2.I am not getting help online. please provide code if possible.

Best Answer

Follow the following Steps:

  1. Create a file Abc.php in Vendor/Module/Console/Command folder.
<?php
namespace Jasvir\Test\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Jasvir\Test\Model\ItemFactory;
use Magento\Framework\Console\Cli;
class AddItem extends Command

{
    const INPUT_KEY_NAME = 'name';
    const INPUT_KEY_DESCRIPTION = 'description';
    const INPUT_KEY_COMMENT = 'comments';
    private $itemFactory;

    public function __construct(ItemFactory $itemFactory)
    {
        $this->itemFactory = $itemFactory;
        parent::__construct();
    }
    /**
     * @inheritDoc
     */
    protected function configure()
    {
        $this->setName('mastering:add:item')
            ->addArgument(
                self::INPUT_KEY_NAME,
                InputArgument::REQUIRED,
                'Item Name'
            )
            ->addArgument(
                self::INPUT_KEY_DESCRIPTION,
                InputArgument::OPTIONAL,
                'Item Description'
            )
            ->addArgument(
                self::INPUT_KEY_COMMENT,
                InputArgument::OPTIONAL,
                'Item Comments'
            );         
        parent::configure();
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @return null|int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $item = $this->itemFactory->create();
        $item->setName($input->getArgument(self::INPUT_KEY_NAME));
        $item->setDescription($input->getArgument(self::INPUT_KEY_DESCRIPTION));
        $item->setComments($input->getArgument(self::INPUT_KEY_COMMENT));
        $item->setIsObjectNew(true);
        $item->save();
        return Cli::RETURN_SUCCESS;
    }
}

Then in command line run the following command:

php bin/magento mastering:add:item "Magento 2 " "It is a CMS" "Comment"

There is some other things you have to consider before this.

Please refer to this video. I followed this whole video and learn a great deal from this.

https://www.youtube.com/watch?v=6ZZtebIv_Ws

Related Topic