Yii2: How do you use named parameters in console commands?

青春壹個敷衍的年華 提交于 2020-01-16 06:14:31

问题


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:

  1. You add the parameters as properties to the controller:
class CustomerController extends Controller {
    public $param1;
    public $param2;
    ...
  1. 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.

  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!