Sets the application instance for this command.
public setApplication ( |
||
$application | An Application instance |
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class GreetCommand extends Command { protected static $defaultName = 'greet'; protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln('Hello world!'); return Command::SUCCESS; } } $app = new Application('My Console App'); $app->add(new GreetCommand()); $command = $app->find('greet'); $command->setApplication($app); $command->run(new ArrayInput([]), new ConsoleOutput());
use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class GreetCommand extends Command { protected static $defaultName = 'greet'; protected function execute(InputInterface $input, OutputInterface $output): int { $appName = $this->getApplication()->getName(); $output->writeln(sprintf('Hello, %s!', $appName)); return Command::SUCCESS; } } $app = new Application('My Console App'); $app->add(new GreetCommand()); $command = $app->find('greet'); $command->run(new ArrayInput([]), new ConsoleOutput());In this example, we modify the GreetCommand to use the getApplication method to retrieve the application name. We remove the setApplication call and instead rely on the default behavior of the command to retrieve the application instance from the command context. We then execute the command as before. Package library: Symfony\Component\Console\Command\Command In both examples, the Command setApplication method is used to set or retrieve the application instance, which is useful for creating stand-alone applications and testing. The library used is Symfony\Component\Console\Command\Command.
public setApplication ( |
||
$application | An Application instance |