How to Call Function from CLI Command in Magento 2

How to Call Function from CLI Command in Magento 2

Hello Magento Friends,

Today I am going to explain How to Call Function from CLI Command in Magento 2.

You can also call a function using a block file from the CLI command to Magento 2. Check out the below steps to learn how to accomplish it.

Steps to Call Function from CLI Command in Magento 2:

Step 1: Firstly, you need to run the below command

php bin/magento example:hicustomer

Step 2: You need to call the block file by creating a di.xml file at the below path.

app\code\Vendor\Extension\etc\di.xml

And add the code as mentioned below

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <type name="Magento\Framework\Console\CommandList">
       <arguments>
           <argument name="commands" xsi:type="array">
               <item name="hicustomer" xsi:type="object">Vendor\Extension\Console\Hicustomer</item>
           </argument>
       </arguments>
   </type>
</config>

Step 3: Now create a file at the following path

app\code\Vendor\Extension\Console\Hicustomer.php

And add the below code

<?php
namespace Vendor\Extension\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class Hicustomer extends Command
{
   protected function configure()
   {
       $this->setName('example:hicustomer');
       $this->setDescription('Demo command line');
       
       parent::configure();
   }
   protected function execute(InputInterface $input, OutputInterface $output)
   {
       $output->writeln("Hello World");
   }
}

Conclusion:

Hence, this way you can Call Function from CLI Command in Magento 2. Check out the list of useful CLI commands for Magento 2. Share your queries via the comment section. Let your friends know about this solution. Stay tuned for the next one!

Happy Coding!

Previous Article

How to Create Customer Groups Programmatically in Magento 2

Next Article

Big News: Get ready for Magento 2.4.4 Beta Releases [Updated]

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨