问题
How can I write the console command yii controller/action --param1=something --param2=anything
and retrieve those named parameters in the action?
回答1:
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
.
来源:https://stackoverflow.com/questions/38812696/yii2-how-do-you-use-named-parameters-in-console-commands