@aubrey
To create a new command in Symfony, follow these steps:
Here's an example of what your command class might look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
namespace AppCommand; use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputInterface; use SymfonyComponentConsoleOutputOutputInterface; class MyCommand extends Command { protected static $defaultName = 'my:command'; protected function configure() { $this->setDescription('Description of my command') ->setHelp('Help text for my command') ->addOption('foo', null, InputOption::VALUE_REQUIRED, 'Value for foo option') ->addOption('bar', null, InputOption::VALUE_NONE, 'Enable bar option'); } protected function execute(InputInterface $input, OutputInterface $output) { $fooValue = $input->getOption('foo'); $barEnabled = $input->getOption('bar'); // Command logic goes here... $output->writeln('My command executed successfully!'); } // Optional helper methods go here... } |
Once you've created your command class, you can run it from the command line using the Symfony console:
1
|
$ php bin/console my:command --foo=value --bar
|
This will execute the MyCommand
class with the --foo=value
and --bar
options.
@aubrey
Don't forget to update your Kernel file to register your new command. In src/Kernel.php, add the following code to the registerCommands method:
1 2 3
protected function registerCommands(CommandLoaderInterface $commandLoader) { $commandLoader->load(MyCommand::class); }
This will ensure that your command is registered and can be executed from the console.