We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Creating a global variable in CLI application

Hi! I'm making a CLI application and I need a global variable (array) which would be accessible throughout multiple tasks and classes. This variable needs to be instantiated once the main script starts running (my server), after which I need to add new items in different places inside the app. How would I do this?

I tried putting it in services, but since this service is a class I'm not sure how to make a unique instance of it and of the array inside of it. I've tried making this class in different ways, including static properties and functions and also this:

class OnlineUsers
{
    private $onlineUsers = null;

    public function getOnlineUsers() {
        if ($this->onlineUsers == null) {
            $this->onlineUsers = [];
        }
        return $this->onlineUsers;
    }

    public function addOnlineUser($user) {
        array_push($this->onlineUsers, $user);
    }

}

In services.php:

$di->setShared('onlineUsers', function () {
    return new OnlineUsers();
});

But no matter how I create it, when adding to array (for example in ChatTask), it always adds one item (the last one), so I'm guessing it's being overwritten or the instance is not persistent even if MainTask is still running so the application is not "done". What am I doing wrong and is there a smarter way of doing what I need?

TL;DR: I'm just trying to have a single global variable that's accessible throughtout my CLI application (either as a plain array or as a class) which I can modify. Could you help me with this?

well the Di is the right way

edited Nov '18
// some controller action
$this->onlineUsers->addOnlineUser('u1');
$this->onlineUsers->addOnlineUser('u2');
echo count($this->onlineUsers->getOnlineUsers()), PHP_EOL;

When run in a single process (cli) / request (web), the output should be 2


// some controller action call #1
$this->onlineUsers->addOnlineUser('u1');
echo count($this->onlineUsers->getOnlineUsers()), PHP_EOL;
// some controller action call #2
$this->onlineUsers->addOnlineUser('u2');
echo count($this->onlineUsers->getOnlineUsers()), PHP_EOL;

When run in a seperate process (cli) / request (web), the output should be 1 in both cases.

If your usecase is the second one, you should use sessions, but that will only work on web