Archive for the ‘task’ Tag
How to create a command (task) 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. Here, you must create a file named MytaskCommand.php with the following code:
<?php namespace Application\VremeaBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\Command; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Razvan\Utils\Curl; class ImportCommand extends Command { const NEWLINE = true; private $connection; protected function configure() { parent::configure(); $this ->setName('tudorica:razvan') ->addArgument('type', InputArgument::REQUIRED, 'Type') ->addOption('country', 'c', InputOption::VALUE_OPTIONAL, 'Country', '') ; } /** * Executes the current command. * * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance * * @return integer 0 if everything went fine, or an error code * * @throws \LogicException When this abstract class is not implemented */ protected function execute(InputInterface $input, OutputInterface $output) { // your code here. //if you want to access database (must to setup doctrine.dbal) $this->connection = $this->container->get('database_connection'); //to get the user input argument "type" for this command $type = $input->getArgument('type'); //to get use option "contry" for this command $country = $input->getOption('country'); //to write a message (in symfony1.x was named log). $output->write('type: '.$type, true); } }
Now, you can open a console and go to app folder. If you write:
./console
you will see something like
nit :acl :bundle router :debug Displays current routes for an application :dump-apache Dumps all routes as Apache rewrite rules tudorica :razvan
You can execute this Command with: ./console tudorica:razvan