Skip to content

PropertyGuard

PropertyGuard is an interface. A class implements it to check every write of its own properties before the value is stored.

The class writes two methods:

  • beforePropertySet(string $name, mixed $value, array<string> $keys): void runs before a write. $value is the new value. $keys is [] for a write of the whole property, and the keys of the element for a write to one element.
  • beforePropertyUnset(string $name, array<string> $keys): void runs before unset removes an element.

If either method throws an error, the write does not happen. Both methods return void, so they cannot change the value. To change a value, use a set hook.

Good to know: a class that does not implement PropertyGuard does no extra work on a write.

Examples

A record that locks after it is saved

<?nvs
// Shows an invoice that cannot change after it is saved. The guard throws an
// error on every write once `$saved` is `true`.
class Invoice implements PropertyGuard
{
public string $customer = '';
public array<int> $lines = [];
public bool $saved = false;
public function beforePropertySet(string $name, mixed $value, array<string> $keys): void
{
if ($this->saved) {
throw new LogicError('the invoice is saved, so ' . $name . ' cannot change');
}
}
public function beforePropertyUnset(string $name, array<string> $keys): void
{
if ($this->saved) {
throw new LogicError('the invoice is saved, so ' . $name . ' cannot change');
}
}
}
var $invoice = new Invoice();
$invoice->customer = 'Shop';
$invoice->lines[] = 120;
$invoice->lines[] = 80;
$invoice->saved = true;
// Each write below throws an error, so the invoice keeps its values.
try {
$invoice->lines[] = 999;
} catch (LogicError $e) {
echo 'error: ', $e->message, "\n";
}
try {
unset($invoice->lines[0]);
} catch (LogicError $e) {
echo 'error: ', $e->message, "\n";
}
// This prints `Shop [120,80]`.
echo $invoice->customer, ' ', Core\Json::encode($invoice->lines), "\n";
Output
error: the invoice is saved, so lines cannot change
error: the invoice is saved, so lines cannot change
Shop [120,80]

Changelog

VersionChange
0.0.5A PropertyGuard whose beforePropertyUnset replaced the array could make unset($object->property[$key]) use the old, freed array. Now the unset removes the key from the array the property has after the guard.