Search code examples
phpconsoleyii2named-parameters

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


How can I write the console command yii controller/action --param1=something --param2=anything and retrieve those named parameters in the action?


Solution

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