14 February 2013

create and execute a command in symfony 2

In Symfony 1.x a task is a command line tool to help perform tasks around the application. The same is in Symfony 2. Unfortunately in Symfony2 there is no tool to auto-generate some code for these. To create a Symfony2 Command you must to have or to create in your Bundle a folder named Command.

Symfony 2 is mainly used to create web application, however, sometimes you need to extend your app and need a command line tool to help perform tasks around the application.

It's one of the most stable parts of the framework and many people have already been using it for several months in many projects as it makes it really easy to develop this kind of software. And of course, everything is done in a really cool way, as many of the parts of Symfony2.

Let’s see how can extremely easy create a new Command Task and custom our output.

Create a file in Command Folder, for instance NewsletterCommand.php and fill it with an empty Command structure as follows

<?php
namespace Ankit\NewsletterBundle\Command;
 
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
 
class NewsletterCommand extends ContainerAwareCommand
{
    protected function configure()
    {
 
        $this
            ->setName('send:newsletter')
            ->setDescription('Sends our daily newsletter to our registered users')
            ;
    }
 
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Starting Newsletter process');
    }
}
You can execute it as:

app/console send:newsletter
The output will be as:
Starting Newsletter process
You can pass some arguments form command too. Lets see how

//addArgument in configure() as 
        $this
            ->setName('send:newsletter')
            ->setDescription('Sends our daily newsletter to our registered users')
            ->addArgument('region', InputArgument::OPTIONAL, 'Where to send?')
            ;
            
//and get this argument in execute() as
       $region = $input->getArgument('region');
       $output->writeln('Sending newsletter to '.$region.' region');
You can execute it as:

app/console send:newsletter India
The output will be as:
Starting Newsletter process
Sending newsletter to India region
Unlike arguments, options are not ordered (meaning you can specify them in any order) and are specified with two dashes (e.g. --India - you can also declare a one-letter shortcut that you can call with a single dash like -I).

Symfony2 will automatically locate and include the command as part of the console commands.

No comments:

Post a Comment