Writing Commands

In addition to the commands provided within Bones, you may also build your own custom commands. Commands are typically stored in the plugin/Console/Commands directory; however, you are free to choose your own storage location as long as your commands can be loaded by Composer.

Generating Commands

To create a new command, use the make:console Bones command. This command will create a new command class in the plugin/Console/Commands directory. Don’t worry if this directory does not exist in your plugin, since it will be created the very first time when running the make:command Bones command. The generated command will include the default set of properties and methods that are present on all commands:

php bones make:console MyCommand

The above command will generate a class at plugin/Console/Commands/MyCommand.php. It will generate the file plugin/Console/Kernel.php if it doesn’t exist. The signature of the command and the command name will be asked in the console.

plugin/Console/Commands/MyCommand.php
<?php
namespace WPKirk\Console\Commands;
 
use WPKirk\WPBones\Console\Command;
 
class MyCommand extends Command
{
 
  protected $signature = 'wpkirk:sample {--name= : Display your name}';
 
  protected $description = 'Example of bones command';
 
  public function handle()
  {
    if( $this->options( 'name' ) ) {
      $this->line( 'Hello, ' . $this->options( 'name' ) );
    } else {
      $this->line( 'Hello, World!' );
    }
  }
}

Command Structure

Once your command is generated, you should fill out the signature and description properties of the class, which will be used when displaying your command on the list screen.

The handle method will be called when your command is executed. You may place any command logic in this method.

You will also need to add the command class in the plugin/Console/Commands/Kernel.php file, in the $command property array.

<?php
namespace WPKirk\Console;
 
use WPKirk\WPBones\Foundation\Console\Kernel as ConsoleKernel;
 
class Kernel extends ConsoleKernel
{
  protected $commands = [
    'WPKirk\Console\Commands\MyCommand',
  ];
}

Customizing Deploy

You can customize the deployment process by using the action wpbones_console_deploy_completed. This is very useful, for example, to delete a folder and write a new file. To do that, you can override the __construct method in your command.

public function __construct()
{
    parent::__construct();
 
    /**
     * Fired when the deploy command is completed
     *
     * @param object $console Instance of WPBones Console
     * @param string $path Destination path
     */
    add_action('wpbones_console_deploy_completed',
        function ($console, $path) {
            $console->deleteDirectory("{$path}/my-folder");
        }, 10, 2);
}

You will find more actions and filters in the deploy.php file in the root of your Bones plugin. That’s another way to customize the deploy process.