Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Custom spark commands

Besides the built-in commands spark can have your own: send out emails, delete old drafts, recalculate statistics. A command is a class run from the terminal instead of the browser, so it may work for a long time. Commands live in the app/Commands folder.

Creating a command

php spark make:command PostsCount

The command creates the file app/Commands/PostsCount.php. Fill in the properties and the run() method:

// app/Commands/PostsCount.php
namespace App\Commands;
 
use App\Models\PostModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
 
class PostsCount extends BaseCommand
{
    protected $group = 'Blog';
    protected $name = 'posts:count';
    protected $description = 'Shows the number of posts';
 
    public function run(array $params)
    {
        $total = model(PostModel::class)->countAllResults();
 
        CLI::write("Posts in the blog: $total");
    }
}

$name is the name the command is called by, $group is the section in the php spark list, $description is the caption in that list. CLI::write() prints a line to the terminal.

Running

php spark posts:count

The terminal prints "Posts in the blog: 20". The command does not have to be registered anywhere: CodeIgniter finds classes in app/Commands by itself.

Arguments and options

Arguments are values after the command name; they arrive in the $params array. Options are written with two hyphens and read with CLI::getOption():

// app/Commands/PostsClean.php
protected $name = 'posts:clean';
protected $usage = 'posts:clean [days] [--dry]';
 
public function run(array $params)
{
    $days = (int) ($params[0] ?? 30);
    $date = date('Y-m-d H:i:s', time() - $days * 86400);
 
    $posts = model(PostModel::class)->where('status', 0)->where('created_at <', $date);
 
    if (CLI::getOption('dry')) {
        CLI::write('To be deleted: ' . $posts->countAllResults());
 
        return;
    }
 
    $posts->delete();
    CLI::write('Drafts deleted', 'green');
}
php spark posts:clean 60 --dry

The command reports how many drafts older than 60 days would be deleted but touches nothing. Without --dry the drafts are deleted.

Terminal output

MethodWhat it does
CLI::write('text', 'green')Prints a line, optionally in colour
CLI::error('text')Prints an error message
CLI::prompt('Continue?', ['y', 'n'])Asks a question and returns the answer
CLI::table($rows, $headers)Prints a table
CLI::newLine()An empty line

Running on a schedule

To make a command run by itself, add it to cron, the server's scheduler. The line below runs the clean-up every night at three o'clock:

0 3 * * * cd /var/www/blog && php spark posts:clean 60

The first five fields are the minute, hour, day of the month, month and day of the week.

Common mistake

A command does not appear in the php spark list if the class has no $group and $name or the namespace does not match the folder. The file app/Commands/PostsCount.php must contain namespace App\Commands; and the class PostsCount. The name used to call it comes from the $name property, not from the class name.

Thanks for reading!

Donate to the site — we work hard for you.