How can I write the console command yii controller/action --param1=something --param2=anything
and retrieve those named parameters in the action?
I found out that the documentation does say how to, but instead of calling it "named parameters" as I expected it to, it is called options: http://www.yiiframework.com/doc-2.0/guide-tutorial-console.html#create-command
The docs is not quite complete though. So here is an example:
class CustomerController extends Controller {
public $param1;
public $param2;
...
options
method to the controller: public function options($actionID) {
return array_merge(parent::options($actionID), ['param1', 'param2']);
}
$actionID
must be specified, and parent::options($actionID)
is used to include any existing options.
$this->param1
and $this->param2
, eg.: public function actionSomething() {
doAnything($this->param1, $this->param2);
}
It's okay to combine non-named and named parameters. The named ones just need to be specified last.
Also lacking from the docs is the fact that if you specify a parameter without a value (eg. --param1
instead of --param1=500
) the value of $this->param1
will be boolean true
. If not specified at all the value will be NULL
.