XF 2.2 How to create a custom CLI command for an add-on?

mazzly

Well-known member
Is there any documentation on how to create a custom command that can be run with php cmd.php xf-rebuild:foo or similar?

I've looked at some other addons and also tried creating relevant files under AddonFolder/Cli/Command but it doesn't seem to be picked up..

I'm surely missing some registration of the command, but I can't seem to find it 🙈
 
1697721076388.webp
XF\Cli\Runner
To implement, use the class
XF\Cli\Command\Rebuild\AbstractRebuildCommand

1697721199973.webp
in the getRebuildName method it will take the name
 
Just extend Symfony\Component\Console\Command\Command. Command is available directly after.

Here's what I did in the past:
PHP:
<?php

namespace MyAddon\Cli\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;

class Test extends Command
{
    protected function configure()
    {
        $this->setName('myaddon:test');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var QuestionHelper $helper */
        $helper = $this->getHelper('question');

        $question = new ConfirmationQuestion('<question> Please confirm that you want to run a test: (y/n)</question>');
        $response = $helper->ask($input, $output, $question);
        if (!$response)
        {
            return 1;
        }

        // your code goes here

        return 0;
    }
}

1697727603666.webp
 
Yeah I just realized I had the namespace missing 🤦‍♂️ Hopefully this helps someone doing the same thing in the future 😅
 
Something to be aware of; when the configure is called there isn't actually an \XF::app() setup yet. Which means add-on options are unavailable when dumping the commands and command arguments.
 
Yeah I just realized I had the namespace missing 🤦‍♂️ Hopefully this helps someone doing the same thing in the future 😅

When copying and pasting an existing command in PhpStorm, I've found it mangles the namespace - has caused me a lot of frustration in recent times when I've been trying to work out why my commands are not showing up. Having the correct namespace is critical!
 
Back
Top Bottom