Phalcon 4 CLI task parameter usage

Phalcon 4 made changes to how CLI task actions accept parameters. In previous versions of Phalcon, parameters would come as an array of parameters.

    public function testAction(array $params)
    {
        //
    }

We modified our CLI bootstrap code to look for flags so we could call our task like this:

php cli.php task action --param1 value1 --param2 value2 --param4 value4

Our action would then get an array of params that looks like this:

[
    'param1' => 'value1',
    'param2' => 'value2',
    'param4' => 'value4',
]

This way, we could add optional paramaters (like param3 in the above example) to our task actions.

In Phalcon4, parameters are sent to the task actions individually and having optional parameters appears to be impossible. Lets say I have a a task action that has four params, two of them optional.

    public function testAction($param1, $param2, $param3 = null, $param4 = null)
    {
        //
    }

How would I call this task using param1, param2, and param4 and not using the optional param3? In all our tests, doing this sends the value of param4 to the $param3 variable.

well you dont have to define it inside the action function. you can just use the dispatcher.

$this->dispatcher->getParam("param1")

or just look at the documentation for it but if you dont know the param's Property name then you can use the indexes


$this->dispatcher->getParam(1)
edited Aug '20

@HudsonNicoletti

$this->dispatcher->getParam("param1")

Would this actually work though? In Phalcon4, the name "param1" is only defined in the task action signature. I dont believe that the dispather would have awareness of it.

$this->dispatcher->getParam(1)

I might be wrong, but wouldnt this be the same result as the problem described above? So if I had four params and #3 and #4 are optional, and then if I only pass #1, #2, and #4, wouldn't the dispatcher think that #4 is actually #3?

Looks like you're not the first person to have this problem, as Phalcon has released an options parser library: https://github.com/phalcon/cli-options-parser

@quasipickle That package hasn't been updated in 6 months. Any idea if it is compatible with Phalcon 4?

No idea. Phalcon 4 is > 6 months old though, so I would imagine it is. It's probably just parsing argv, so it's probably pretty Phalcon agnostic.

If it does fail, one I often use (as I just discovered that package myself) is PHP League's CLIMate: https://climate.thephpleague.com/