Create a custom console command

EXT:my_extension/Classes/Command/MyCommand.php

 

<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
name: 'myextension:dosomething',
description: 'A command that does nothing and always succeeds.',
aliases: ['examples:dosomethingalias'],
)]

class DoSomethingCommand extends Command {
protected function configure(): void
{
$this->setHelp('This command does nothing. It always succeeds.');
}

protected function execute(InputInterface $input, OutputInterface $output): int {
$io = new SymfonyStyle($input, $output);
$io->info('Command needs to be implemented. ');
return Command::SUCCESS;
}
}
 

 

Execute in console:

Composer:

 

vendor/bin/typo3 cache:flush
vendor/bin/typo3 examples:dosomething

 

Legacy-mode:

 

typo3/sysext/core/bin/typo3 cache:flush
typo3/sysext/core/bin/typo3 examples:dosomething

Register command as a service

Register in Configuration/Services.yaml:

 

Vendor\Extkey\Command\className:
tags:
- name: 'console.command'
command: 'extkex:className'
description: 'Make a lot of people happy'
schedulable: true
hidden: false
 

 

https://docs.typo3.org/m/typo3/reference-coreapi/main/en-us/ApiOverview/CommandControllers/CustomCommands.html#making-a-command-non-schedulable

 

Use Services in your command class

Create a file in your extension in Classes/Service/YourService.php

use with:
use Vendor/Extkey/Service/YourService
in your class: $this→YourService→doSomething();

 

 

<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Vendor/Extkey/Service/YourService;

#[AsCommand(
name: 'myextension:dosomething',
description: 'A command that does nothing and always succeeds.',
aliases: ['examples:dosomethingalias'],
)]

class DoSomethingCommand extends Command {
protected function configure(): void
{
$this->setHelp('This command does nothing. It always succeeds.');
}

protected function execute(InputInterface $input, OutputInterface $output): int {
$io = new SymfonyStyle($input, $output);

$this→YourService→doSomething();

return Command::SUCCESS;
}
}