问题描述
如何编写控制台命令 yii controller / action --param1 = something --param2 = anything
并在操作中检索这些命名参数?
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;
...
-
选项
方法到控制器:
- You add the
options
method to the controller:
public function options($actionID) {
return array_merge(parent::options($actionID), ['param1', 'param2']);
}
$ actionID
parent :: options($ actionID)
用于包含任何现有的选项。
$actionID
must be specified, and parent::options($actionID)
is used to include any existing options.
- 现在,您可以使用
$ this-> param1
和$ this- ; param2
,例如:
- 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.
如果你指定一个没有值的参数(例如 - param1
而不是 - param1 = 500
)的值 $ this-> param1
将为布尔 true
。如果没有指定,则 NULL
。
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
.
这篇关于Yii2:如何在控制台命令中使用命名参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!