Plugin Development: Commands

Previous Section: Sending Email


Plugins can be used to register your own Artisan commands that are run on the command line interface (CLI). This is particularly useful for tasks that are resource extensive, may take a long time and you do not wish to run on the web server. Commands should be used in favour of scheduled tasks, which are also ran on the CLI, when the task is not recurring or needed on a schedule.

Contents

Writing a Command

A command must extend the \Illuminate\Console\Command class, we've included an example command below. The command has an optional argument user, and will initially display a greeting Hello [user]!. If the user argument is not entered, it will show Hello world! instead. The command will then ask how old you are, and display a line based on the age entered.


<?php
/**
 * Hello command for HelloWorld Plugin.
 *
 * @package    Addons\Plugins\HelloWorld\Commands
 * @copyright  Copyright (c) 2015-2019 SupportPal (http://www.supportpal.com)
 * @license    http://www.supportpal.com/company/eula
 */
namespace Addons\Plugins\HelloWorld\Commands;

use Illuminate\Console\Command;

/**
 * Class Hello
 *
 * @package    Addons\Plugins\HelloWorld\Commands
 * @copyright  Copyright (c) 2015-2019 SupportPal (http://www.supportpal.com)
 * @license    http://www.supportpal.com/company/eula
 */
class Hello extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'hello {user?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Greetings.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $user = $this->argument('user') ?? 'world';

        $this->info("Hello {$user}!");

        $age = $this->ask('How old are you?');

        $this->info("Wow, you are " . $age . " years old!");
    }
}

Registering a Command

The command must then be registered in the main controller constructor using the registerCommand helper.

Controllers/HelloWorld.php

    /**
     * Initialise the plugin
     */
    public function __construct()
    {
        parent::__construct();

        $this->setIdentifier('HelloWorld');

        // Register a console command, accessible via 'php artisan <name>'.
        $this->registerCommand(\Addons\Plugins\HelloWorld\Commands\Hello::class);
    }

Calling a Command

When the plugin that contains this command is enabled, the command can be run on the CLI (in the base SupportPal directory) by entering php artisan hello or php artisan hello Joe.

Plugin Command

We recommend to read over the Artisan documentation for more information on what can be done with commands.


Next Section: Upgrading