Search code examples
symfonysymfony-2.7

Can I store a value between executions of a Symfony2 command?


I already know I can't just store it as a protected variable on the Command Class itself (I tried it and that doesn't work). Is there a way to store data between executions of a command without storing that information in the database or writing to a file?

Basically, I'm running a command through cron every 2 minutes, but I want to set a flag that changes every time I run the command.

The following doesn't work, as the protected variable is initialized to snc_redis.dashboard1 every time I run the command.

protected $redisDb = 'snc_redis.dashboard1';

protected function execute(InputInterface $input, OutputInterface $output)
{
    if ( $this->redisDb == 'snc_redis.dashboard1') {
        $this->redisDb = 'snc_redis.dashboard2';
    }
    else {
        $this->redisDb = 'snc_redis.dashboard1';
    }
}

Solution

  • I already know I can't just store it as a protected variable on the Command Class itself (I tried it and that doesn't work).

    This is because each time you run the command it's a new process.

    Is there a way to store data between executions of a command without storing that information in the database or writing to a file?

    No.

    Again, each command is run in a separate process, so there's no memory shared between them. Event storing your stuff with APCu won't work (for the same reason).

    If you want to persist something between runs you'll need to store it some kind of cache that can be shared between processes (like filesystem, database, redis/memcached etc).