Posts

Showing posts with the label command

Controllers as Services in Symfony2

Controller as a service is continually touted as the best practice. But why would I wrap a controller into a service? That's good question. Well, the point of doing this in general is not having to inject the DI container into your controllers (instead, you inject the dependencies into the controller directly). Thus the controller no longer depends on the container. Good: You get added flexibility. You no longer hard-code which services to use into your controller. You can specify that in the DI configuration instead. Example: You inject a UserProvider into the UserController for /profile, but inject a FacebookUserProvider into the same UserController for /profile/facebook. Bad: You must manually configure your dependencies in the DIC config. You need to manually assign the injected dependencies. Optional dependencies are no longer lazy-loaded. This is basically just a proof of concept to show how it could be done. namespace Acme\DemoBundle\Controller; class FooContr...

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 ...