Skip to content

$this->bga->globals

Store values for the current table in the bga_globals database table. Values are serialized as JSON; use scalars, arrays, or serializable data objects. Each call reads or writes the database rather than a local cache.

API

set(string $name, mixed $obj): void

Create or replace a value. Use developer-defined keys of at most 50 characters, preferably constants.

get(string $name, mixed $defaultValue = null, ?string $class = null): mixed

Read a value, returning $defaultValue if the key does not exist. To reconstruct an object as a particular class, pass class: MyClass::class. Use a data class whose constructor parameter names match its stored properties.

getAll(string ...$names): array

Return values keyed by name. With no arguments, return every stored global. With names, return only matching keys; missing keys are omitted.

has(string $name): bool

Check whether a key exists, including a key whose stored value is null.

inc(string $name, int $inc): int

Add to an existing integer and return its new value. An absent or non-integer value causes an exception. Use a negative increment to subtract.

delete(string ...$names): void

Delete the specified keys. With no arguments, nothing is deleted.

Example

// In setupNewGame:
$this->bga->globals->set('round', 1);

// When starting another round:
$round = $this->bga->globals->inc('round', 1);

Arrays and data objects

JSON serialization cannot store functions or circular references. Without a class argument, a stored object is read as stdClass.

$this->bga->globals->set('selectedCards', [3, 8]);
$selectedCards = $this->bga->globals->get('selectedCards', []);

$this->bga->globals->set('pendingChoice', (object) ['playerId' => $playerId]);
$choice = $this->bga->globals->get('pendingChoice');

To restore a specific class, define a data object. Optional constructor arguments make it straightforward to create an empty instance:

class PendingChoice
{
    public function __construct(
        public ?int $playerId = null,
        public array $cardIds = [],
    ) {}
}

$this->bga->globals->set('pendingChoice', new PendingChoice($playerId, [3, 8]));
$choice = $this->bga->globals->get('pendingChoice', class: PendingChoice::class);

Reading and deleting several values

$values = $this->bga->globals->getAll('round', 'selectedCards');
$round = $values['round'] ?? 1;
$selectedCards = $values['selectedCards'] ?? [];

// Alternatively, assign variables from trusted, developer-defined keys.
extract($this->bga->globals->getAll('round', 'selectedCards'));

if ($this->bga->globals->has('pendingChoice')) {
    $this->bga->globals->delete('pendingChoice', 'selectedCards');
}