Additionally/Accessibility/Console commands/Customizable command options

Configurable Command Options

Initially, the options for executing console commands are set in the 'run' method of the command class. They correspond to the method's argument order.

In the HLEB2 framework, you can also specify one or several named parameters for a command. The order of named parameters does not matter when invoking the command.


#rules() Method

The rules() method of the command class returns an array with rules for extended parameters. If such a method does not exist, add it as the first method of the command class.

#[\Override]
protected function 
rules(): array
{
    return [
        
Arg(name'Name')->short(name'N')->default('Undefined')->required(),
        
Arg(name'force'),
        
Arg(name'UserData')->list()->default([]),
    ];
}

The example shows three different named parameters of different types. The parameter name is mandatory and must not be duplicated.

The first parameter supports two values -N and --Name, its presence is required. By default, --Name is equal to the string 'Undefined', and the incoming value can only be a string (not an array). The value can be in the form --Name=Fedor or -N=Mark, while --Name will be equal to 'Undefined'.

The second parameter is of the form --force (without a value); if present, it equals true.

The third parameter is in the form of an array, and the value can be specified multiple times, such as --UserData=1 and --UserData=2, which is equivalent to --UserData=[1,2]. Its presence is optional, and if there is no value or it is called like --UserData, it will be equal to [] (an empty array).


#Retrieving Parameter Values

The parameter data can be obtained as $this->getOptions() or $this->getOption() in the run() method of the command. The first method returns a named array of system objects, from each of which you can get the value in the required format. The other returns a similar system object of one parameter by name (mandatory main, not short).

$name $this->getOption('Name')->asString();

$force $this->getOption('force')->asBool();

$options $this->getOption('UserData')->asArray();
Page translated: chatgpt 4-o
Back to top