Write a Simple CLI Command using Symfony

CLI Command using Symfony

Using Symfony framework developers can create various types of commands which can be executed by consoles. Symfony already provides lots of console commands, Like php app/console cache:clear or php bin/console doctrine:mapping:import --force AcmeBlogBundle xml.

Now if we want to create a command like those for our own, like running cron jobs or export database using a command etc this post can help us to set up a simple command.

Command Structure

Say, we have an Application bundle named SmsBundle. We need to define our command class under Command namespace in the SmsBundle and the file should have Command in the end.
So, for the SendSms will have to maintain the following structure

// this is the file structure of the command file
// src/SmsBundle/Command/SendSmsCommand.php
namespace SmsBundle\Command;

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

class SendSmsCommand extends Command
{
    protected function configure()
   {
           // necessary codes
    }

    protected function execute(InputInterface $input, OutputInterface $output)
   {
           // necessary codes
   }
}

This is the basic structure of a command. Now we need to configure this to run according to our needs.

Taking inputs and Showing Outputs

For taking inputs and showing proper outputs based on inputs first we need to use configure our configure and execute methods.
Here is an example how to configure these methods in the following code snippet

Here, we can see the process how to take inputs from console and show the proper output in console. Also we added the configuring code in the snippet. I hope the comments can be very helpful to understand the code.

Running the Command

Now it's time to run our custom command. Let's see how we will be running our codes.

$ php app/console sms:send +8801413981571 Hello SMS from Symfony Command.
Sending a SMS to the number -> +8801413981571
----##--------##----

SMS Sent -> +8801413981571. with a message: Hello SMS from Symfony Command.

Here, +8801413981571 and Hello SMS from Symfony Command. are the two arguments or inputs which we defined in the configure method earlier.

You can look the code snippet from gist.

Now you can use it to create any command in Symfony, enjoy!

comments powered by Disqus