XF 2.1 How do I create a CLI function for my add-on?

AndyB

Well-known member
Hello,

I currently have an add-on called Amazon parser all. The latest version allows running from Rebuild caches. I would also like to learn how to create a CLI option for this add-on.

So far I have created a Cli/Command/AmazonParserAll.php file. My question is what code do I use in the AmazonParserAll.php file? I assume I will use primarily the same code I used in my Job/AmazonParserAll.php file, but what changes do I need to make?

Job/AmazonParserAll.php

PHP:
<?php

namespace Andy\AmazonParserAll\Job;

use XF\Job\AbstractRebuildJob;
use XF\Mvc\Entity\Entity;

class AmazonParserAll extends AbstractRebuildJob
{
    protected $defaultData = [
        'start' => 0,
        'batch' => 100
    ];
   
    protected function getNextIds($start, $batch)
    {
        $db = $this->app->db();
       
        return $db->fetchAllColumn($db->limit(
            "
                SELECT post_id
                FROM xf_post
                WHERE post_id > ?
                ORDER BY post_id
            ", $batch
        ), $start);
    }
...

Thank you.
 
Last edited:
Look at any of the core classes that subclass \XF\Cli\Command\Rebuild\AbstractRebuildCommand. It's mostly a matter of providing a name, description, and accompanying job class. You run the job from the command, not duplicate it.
 
Thank you for your time, Jeremy.

I created this file:

1571958436745.png

PHP:
<?php

namespace Andy\AmazonParserAll\XF\Cli\Command\Rebuild;

class RebuildAmazonParserAll extends AbstractRebuildCommand
{
    protected function getRebuildName()
    {
        return 'amazonparserall';
    }

    protected function getRebuildDescription()
    {
        return 'Rebuilds amazon parser all.';
    }

    protected function getRebuildClass()
    {
        return 'Andy\AmazonParserAll';
    }
}

I get the following error:

1571958645015.webp
 
Last edited:
It's not extending a core class, so it shouldn't be namespaced under an XF directory. And you'll need to import the abstract class.
 
Thank you, Jeremy. I really appreciate your help.

Here's the correct code:

1571964517646.webp

RebuildAmazonParserAll.php

PHP:
<?php

namespace Andy\AmazonParserAll\Cli\Command\Rebuild;

use XF\Cli\Command\Rebuild\AbstractRebuildCommand;

class RebuildAmazonParserAll extends AbstractRebuildCommand
{
	protected function getRebuildName()
	{
		return 'amazonparserall';
	}

	protected function getRebuildDescription()
	{
		return 'Rebuilds amazon parser all.';
	}

	protected function getRebuildClass()
	{
		return 'Andy\AmazonParserAll\Job\AmazonParserAll';
	}
}

To run from CLI:

php cmd.php xf-rebuild:amazonparserall
 
Back
Top Bottom