20 February 2013

run symfony command from controller

Hi Friends,
Few month back I was trying to execute Symfony2 command in my controller. See how can we do that.

Step 1

Register you command as service
  
MyCommandService:
    class: MyBundle\Command\MyCommand
    calls:
        - [setContainer, ["@service_container"] ]
    
 

Step 2

In your controller, you'll just have to get this service, and call the execute method with the rights arguments. Set the input with setArgument method:
  
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
.
.
.
public function myAction() {
  $command = $this->get('MyCommandService');
  
  $input = new ArgvInput(array('arg1'=> 'value'));
  $output = new ConsoleOutput();
  $command->run($input, $output);
}
    
 

Step 3

Either you can use the execute method of command:
   
$command->execute($input, $ouput);
    
 
But see the defination of run() and execute() methods.

  • run () -: The code to execute is either defined directly with the setCode() method or by overriding the execute() method in a sub-class. 
  • execute () -: This method is not abstract because you can use this class as a concrete class. In this case, instead of defining the execute() method, you set the code to execute by passing a Closure to the setCode() method.

1 comment:

  1. Does the Command extend Command or ContainerAwareCommand ?

    ReplyDelete