How can I write the console command yii controller/action --param1=something --param2=anything
and retrieve those named parameters in the action?
Asked
Active
Viewed 2,228 times
1

TheStoryCoder
- 3,403
- 6
- 34
- 64
1 Answers
0
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:
- You add the parameters as properties to the controller:
class CustomerController extends Controller {
public $param1;
public $param2;
...
- You add the
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.
- You can now access the parameters within your action with
$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
.

TheStoryCoder
- 3,403
- 6
- 34
- 64
-
why not just call `parent::options($actionID)` instead of `Controller::options($actionID)`. You're opening yourself to a world of hurt like this if you ever refactor code. – Blizz Aug 10 '16 at 08:26
-
Didn't think of that! But of course that's a better way to do it. Have adjusted answer. – TheStoryCoder Aug 11 '16 at 06:42