·

photo credit: The Internet Archive via photopin (license)

Utilising Magento 2’s CLI Possibilities

Some of you might already know this, but I’m a great fan of the command line. In web development, I use PHP to write CLI scripts more than often. They provide a great way if you need to perform quick tasks on the server, or if you want to perform tasks after a deployment. If you wanted to use this way of working in Magento 1, you often needed to write scripts that started with the inclusion and instantiation of the Magento framework. With Magento 2, using the CLI to the fullest has become easy as 1,2,3.


Please note that we use the boilerplate module from the article ‘Creating a module in Magento 2‘ as the entry point for this article.

What is the ‘CLI’?

CLI stands for Command Line Interface, and is a very basic way of accessing your system. Those who ever worked with DOS might recognise it (damn I’m old!). Ever worked with the Terminal or logged in with SSH? Then you’ve probably already seen the CLI for yourself. Heck, if you installed or developed with Magento 2, you might already have performed some setup:upgrade  and module:enable -commands. These commands are part of Magento 2’s core CLI options. When you navigate to the bin -folder of your Magento 2 installation, add executable rights to the magento -file and execute it, you’ll see a ton of options:

The commands listed here can be executed from the terminal, so if you type:

… the cache gets cleared without the need to log in to the admin panel. Ideal for after a deployment or update.

Adding CLI options to your own module

So let’s say you have a module that needs to some magic stuff from the terminal. This can be a post-deployment task like deleting files or re-indexing some database tables, but also tasks that can help you locally with development, like scaffolding. How can you add these tasks? Well, to begin you have to let Magento know that you are going to use the CLI: you have to register your classes. This can be done in the di.xml -file of your module:

And in our module, we create a folder called Console , and in that folder we place the file Example.php :

That’s it! There’s all there’s to it! Now, when you execute ./magento , you’ll see your command in the list:

And note the use of arguments, so you can provide extra options from the command line:

This post is part of the series Magento 2 Development from Scratch.

Visitors give this article an average rating of 4.5 out of 5.

How would you rate this article?

Leave a Reply