mae
mae

Reputation: 15656

Yii2: How to pass associative array as commandline argument?

The documentation explains how to use arrays as commandline arguments (by providing a comma-separated list of strings), however this only works for a 1-dimensional indexed array of strings:

// The command "yii example/add test" will call "actionAdd(['test'])"
// The command "yii example/add test1,test2" will call "actionAdd(['test1', 'test2'])"
public function actionAdd(array $name) { ... }

But how do I pass multi-dimensional associative arrays as commandline arguments without relying on hacky json-based workarounds?

At the very least I would like to be able to do something like $ yii example/add "foo=bar" that would execute actionAdd(['foo'=>'bar']). Eventually I would like to also have the ability to do this with nested values (eg. foo.bar=5 being translated to ['foo'=>['bar'=>5]]).

Upvotes: 0

Views: 645

Answers (1)

Виктор 78
Виктор 78

Reputation: 21

There is such code in \yii\console\Controller::bindActionParams

$args[$i] = $args[$i] === '' ? [] : preg_split('/\s*,\s*/', $args[$i]);

So, by default parsing only for comma separated values (non-associative). You can override this method according to your requirements.

But the regexps will be too complex as for me. I advice to use json string for input and then do json_decode().

Upvotes: 1

Related Questions