Property hooks
A property can have a get hook and a set hook. PropertyGuard checks every write of a class’s
properties, and PropertyObserver sees every read and write. A class that implements neither
interface runs no extra code.
get and set hooks
A property hook is a small piece of code that runs every time a property is read or written.
You write get to decide what a read gives back, and set to decide what a write stores. Either one may stand alone. A property with only a get hook is a computed property: it works out its value from the other properties, and only its own class writes it.
The hooks run for every read and every write, including the ones the constructor makes, the ones inside a string, and the ones a subclass makes. Inside the hooks, $this->name is the stored value itself, so a set hook stores with $this->name = ... and does not call itself. A set hook that throws an error stops the write, and the property keeps the value it had.
The examples below show a set hook that checks a value, a get hook that works one out, and a class that keeps a name and a display form in step. Example 04 does not compile.
A set hook checks every write
<?nvs// Shows a `set` hook. It runs on every write, including the one the// constructor makes, so the property can never hold a value outside its range.
class Volume{ public int $level { set(int $v) { if ($v < 0) { throw new LogicError('a volume is never below 0'); } // Inside the hook, `$this->level` is the stored value. This line // stores it, and does not call the hook again. if ($v > 10) { $this->level = 10; } else { $this->level = $v; } } }
public function constructor(int $start) { $this->level = $start; }}
// 30 is above the ceiling, so the hook stores 10.var $radio = new Volume(30);echo $radio->level, "\n";
$radio->level = 7;echo $radio->level, "\n";
// A hook that throws stops the write. The property keeps the value it had.try { $radio->level = -1;} catch (LogicError $e) { echo 'refused: ', $e->message, "\n";}echo $radio->level, "\n";107refused: a volume is never below 07A get hook works the value out
<?nvs// Shows a `get` hook alone. The property stores nothing of its own. It works// its value out from the other properties every time it is read.
class Cart{ public function constructor(public int $unitCents, public int $quantity) {}
// `get => expr;` is short for `get { return expr; }`. public int $totalCents { get => $this->unitCents * $this->quantity; }}
var $cart = new Cart(250, 3);echo $cart->totalCents, "\n";
// The value follows the properties it is worked out from.$cart->quantity = 4;echo $cart->totalCents, "\n";
// A read inside a string runs the hook as well.echo "the cart costs $cart->totalCents cents\n";7501000the cart costs 1000 centsTwo properties kept in step
<?nvs// Shows both hooks on one property. A user's e-mail address is stored in// lower case whatever the form sends, and the display name follows the value// that was stored.
class User{ public string $email { get => $this->email; set(string $v) { string $clean = Core\Str::trim(Core\Str::lower($v)); if (!Core\Str::contains($clean, '@')) { throw new LogicError('that is not an e-mail address'); } $this->email = $clean; } }
// `Core\Str::before` gives the text in front of the `@`. It returns `null` // when there is no `@`, and `??` uses the whole address then. public string $display { get => Core\Str::before($this->email, '@') ?? $this->email; }
public function constructor(string $email) { $this->email = $email; }}
// The form sent spaces and capital letters. The hook cleans both away.var $user = new User(' Ada.Lovelace@Example.COM ');echo $user->email, "\n";echo $user->display, "\n";
// A later write goes through the same hook.$user->email = 'BO@example.com';echo $user->email, ' ', $user->display, "\n";
try { $user->email = 'not-an-address';} catch (LogicError $e) { echo 'refused: ', $e->message, "\n";}echo $user->email, "\n";ada.lovelace@example.comada.lovelacebo@example.com borefused: that is not an e-mail addressbo@example.comAn element write through a hook
<?nvs// Shows that you cannot write one array element through a hooked property,// so this does not compile. Copy the array to a variable, change it there,// and assign the variable back.// proof: compile-error
class Box{ public array<int> $xs { get => $this->xs; set(array<int> $v) { $this->xs = $v; } }
public function constructor() { $this->xs = []; }}
var $b = new Box();$b->xs[0] = 1;error[E0478]: an array element cannot be written through the hooked property `xs` --> 04-an-element-write-through-a-hook.nvs:23:1 |23 | $b->xs[0] = 1; | ^^^^^^ reading this runs its `get` hook = help: a property with hooks is read and written through its hooks. Read it into a variable, write the element there, and assign the variable back to the property
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A get hook can also have a body: get { return $this->a * 3; }. A set hook may leave out its parameter. The new value is then $value, as in set { $this->a = $value; }. A get hook that returns another type than the property is the error E0401.
A hooked property has no default value. public int $a = 3 { … } is a syntax error (E0101). A hook on a promoted constructor parameter is a syntax error too. A readonly property cannot have a hook, which is the error E0843. An interface declares no property, so a hook there is E0254.
A write from outside the class to a property with only a get hook is the error E0787. The class's own methods may write it. The get hook then reads the stored value. A write of one array element through a hooked property is the error E0478, in the class's own methods too. This includes $this->xs[] = 1 in the constructor.
Inside the property's own hooks, $this->name is the stored value. In every other method of the class, $this->name runs the hooks. So $this->a = $this->a + 1 in another method runs get and then set. A compound assignment such as $c->a += 5 and an increment such as $c->a++ run both hooks too. unset($c->a) is the error E0413, as for every property.
A subclass inherits the hooks. A write in a subclass method runs the parent's set hook. A subclass may declare the property again with its own hooks, and a read then runs the subclass's get hook. isset($c->a) runs the get hook, and is false when it returns null.
Two get hooks may read each other, such as get => $this->b on $a and get => $this->a on $b. They then call each other until the program stops with a RecursionError.
PropertyGuard
A class can check every write of its own properties before the value is stored. It implements the interface PropertyGuard.
You write two methods. Novis calls beforePropertySet before every write of a property the class declares, in the constructor too. It gets the name of the property, the new value and a list of keys, $keys. A write of the whole property gives []. A write to one element gives the keys of that element, for example ["0", "1"] for $sheet->cells[0][1] = $v. Novis calls beforePropertyUnset before unset removes an element.
If one of these methods throws an error, nothing changes. The property keeps its old value, and no PropertyObserver method runs.
Good to know: on a property with a set hook, the guard runs before the hook. It gets the value the caller wrote.
Stopping a bad value
<?nvs// Shows a guard that stops a bad write. `Account` throws an error when a// program writes a negative balance, so the old balance stays.
class Account implements PropertyGuard{ public int $balance;
public function constructor(int $balance) { // The guard also checks this write. $this->balance = $balance; }
// `$value` is the new value. It is not stored yet. public function beforePropertySet(string $name, mixed $value, array<string> $keys): void { if ($name == 'balance' && $value is int && $value < 0) { throw new LogicError('the balance cannot be negative'); } }
public function beforePropertyUnset(string $name, array<string> $keys): void { }}
var $account = new Account(100);$account->balance = 40;echo $account->balance, "\n";
try { $account->balance = -10;} catch (LogicError $e) { echo 'error: ', $e->message, "\n";}
// The write did not happen, so this prints 40.echo $account->balance, "\n";40error: the balance cannot be negative40Checking one element
<?nvs// Shows the keys a guard gets for a write to one element. `Profile` allows// at most three tags and does not allow a program to remove the tag "user".
class Profile implements PropertyGuard{ public array<string> $tags = [];
// For `$p->tags[] = "x"`, `$keys` is the next index and `$value` is "x". public function beforePropertySet(string $name, mixed $value, array<string> $keys): void { echo 'set ', $name, ' ', Core\Json::encode($keys), ' = ', $value, "\n"; if (Core\Arr::count($this->tags) >= 3) { throw new LogicError('a profile has at most three tags'); } }
// For `unset($p->tags[0])`, `$keys` is `["0"]`. public function beforePropertyUnset(string $name, array<string> $keys): void { echo 'unset ', $name, ' ', Core\Json::encode($keys), "\n"; if ($this->tags[$keys[0]] == 'user') { throw new LogicError('the tag user cannot be removed'); } }}
var $profile = new Profile();$profile->tags[] = 'user';$profile->tags[] = 'admin';$profile->tags[] = 'beta';
try { $profile->tags[] = 'extra';} catch (LogicError $e) { echo 'error: ', $e->message, "\n";}
try { unset($profile->tags[0]);} catch (LogicError $e) { echo 'error: ', $e->message, "\n";}
echo Core\Json::encode($profile->tags), "\n";set tags ["0"] = userset tags ["1"] = adminset tags ["2"] = betaset tags ["3"] = extraerror: a profile has at most three tagsunset tags ["0"]error: the tag user cannot be removed["user","admin","beta"]A guard and an observer together
<?nvs// Shows the order of the calls when a class has a guard, a `set` hook and an// observer. The guard runs first, and a write it stops reaches nothing else.
class Contact implements PropertyGuard, PropertyObserver{ public string $email { set(string $value) { echo " set hook\n"; $this->email = Core\Str::lower($value); } }
public function constructor(string $email) { $this->email = $email; }
// The guard gets the value the program wrote, before the hook changes it. public function beforePropertySet(string $name, mixed $value, array<string> $keys): void { echo ' guard ', $value, "\n"; if ($value is string && !Core\Str::contains($value, '@')) { throw new LogicError('an email needs an @'); } }
public function beforePropertyUnset(string $name, array<string> $keys): void { }
public function onPropertyGet(string $name, mixed $value): void { }
// The observer gets the value that was stored. public function onPropertySet(string $name, mixed $value): void { echo ' observer ', $value, "\n"; }}
echo "new:\n";var $contact = new Contact('Ada@Example.com');
echo "a bad write:\n";try { $contact->email = 'nobody';} catch (LogicError $e) { echo ' error: ', $e->message, "\n";}echo $contact->email, "\n";new: guard Ada@Example.com set hook observer ada@example.coma bad write: guard nobody error: an email needs an @ada@example.comDetails
A default value is not a write, so it does not call beforePropertySet. A write of a property the class declares calls it, and so does a write of a property a subclass declares. A write through a mixed variable calls it too. A static property calls no guard.
$value has the type mixed. To use it as an int, test it first with $value is int. A plain int $n = $value; is the error E0401.
For a nested element, $keys lists every key from the property down to the element. So $a->cells["r"][0] = 9 gives ["r", "0"]. A compound assignment and an increment give the new value in $value. When $a->x is 1, $a->x += 4 gives 5, and then $a->x++ gives 6.
A guard may write another property of its own class. That write calls the guard again, with the other property's name. Test $name first, or the program calls the guard until the call stack is too deep.
When beforePropertyUnset throws an error, unset removes nothing, and the error goes to the caller.
PropertyObserver
A class can watch every read and every write of its own properties by implementing the interface PropertyObserver.
You write two methods, onPropertyGet and onPropertySet. Novis calls them for every property the class declares: public or private, with hooks or without, written in the constructor or later, and declared by a subclass too. Each call gives you the property name and the value after it has settled, so onPropertySet sees what was really stored. A write to one element, such as $account->history[] = 5, calls onPropertySet once with the whole array after the change.
An observer reports, and it does not decide. Both methods return nothing, so they cannot change the value a read gives back. If a method throws an error, the read or the write throws it. The value of a write is already stored then.
Good to know: writing a property inside one of these two methods calls the method again. Test the name first, or the program runs until the call stack is too deep.
The examples below show the two methods on a small class, how far one observer reaches, and a record that knows when it needs saving.
Watching every read and write
<?nvs// Shows the two methods an observer writes. `Account` prints one line for every// read and every write of its own properties.
class Account implements PropertyObserver{ public string $owner; public int $balance;
public function constructor(string $owner) { // The constructor writes both properties, so `onPropertySet` runs twice here. $this->owner = $owner; $this->balance = 0; }
// `$name` is the property, and `$value` is the value it now has. public function onPropertyGet(string $name, mixed $value): void { echo 'read ', $name, ' = ', $value, "\n"; }
public function onPropertySet(string $name, mixed $value): void { echo 'wrote ', $name, ' = ', $value, "\n"; }}
var $account = new Account('Ada');$account->balance = 120;
// A read calls `onPropertyGet` first, then gives you the value. This prints// the line from the observer and then 120.echo $account->balance, "\n";wrote owner = Adawrote balance = 0wrote balance = 120read balance = 120120One observer for every property
<?nvs// Shows how far one observer reaches. A private property, a property with a// hook, and a property a subclass declares all call the same two methods.
class Record implements PropertyObserver{ private int $id; public string $title;
// The `set` hook stores the lower case text. The observer is told what the // hook stored, not what was written. public string $slug { set(string $v) { $this->slug = Core\Str::lower($v); } }
public function constructor(int $id, string $title) { $this->id = $id; $this->title = $title; $this->slug = $title; }
public function onPropertyGet(string $name, mixed $value): void { echo 'read ', $name, "\n"; }
public function onPropertySet(string $name, mixed $value): void { echo 'wrote ', $name, ' = ', $value, "\n"; }}
// A subclass inherits the two methods, and the property it adds is observed too.class Article extends Record{ public int $words;
public function constructor(int $id, string $title, int $words) { $this->words = $words; parent::constructor($id, $title); }}
var $article = new Article(7, 'Hello World', 240);$article->words = 250;echo $article->title, "\n";wrote words = 240wrote id = 7wrote title = Hello Worldwrote slug = hello worldwrote words = 250read titleHello WorldA record that knows it changed
<?nvs// Shows what an observer is most often used for: a record that knows whether// it still matches the database, so a program saves it only after a change.
final class Contact implements PropertyObserver{ public string $name; public string $email; public bool $unsaved = false;
public function constructor(string $name, string $email) { $this->name = $name; $this->email = $email; // The two writes above set the flag. This row comes from the database, // so it starts as saved. $this->unsaved = false; }
public function onPropertyGet(string $name, mixed $value): void { }
public function onPropertySet(string $name, mixed $value): void { // Writing a property in this method calls the method again. Test the // name first. Without this test the program never stops. if ($name != 'unsaved') { $this->unsaved = true; } }
public function save(): void { if (!$this->unsaved) { echo "nothing to save\n"; return; } echo 'saving ', $this->name, "\n"; $this->unsaved = false; }}
var $contact = new Contact('Ada', 'ada@example.com');$contact->save();
// One write anywhere in the program is enough. No method has to remember to// report it.$contact->email = 'ada.lovelace@example.com';$contact->save();$contact->save();nothing to savesaving Adanothing to saveDetails
A default value is not a write, so it does not call onPropertySet. A static property calls neither method.
onPropertySet runs after the value is stored. If it throws an error, the write throws that error, and the property already has the new value. onPropertyGet runs after the value is read, and an error it throws comes out of the read.
A read inside a string, such as "v=$o->x", calls onPropertyGet. So does isset($o->x). A write of one element, such as $a->rows[] = 1, calls onPropertySet once with the whole array. unset($a->rows[0]) does the same. Neither one calls onPropertyGet.
For a property with a get hook, onPropertyGet gets the value the hook returned. A property the hook reads calls onPropertyGet too, before it. A read inside onPropertyGet of another property calls onPropertyGet again, for that property.
$value has the type mixed. Text you build from it, such as $value as string, is a tainted string, so string $s = $value as string; is the error E0401.
The reference pages of PropertyGuard and
PropertyObserver have one more example each.
Do and don’t
Section titled “Do and don’t”- Do use a
sethook to check a value before it is stored. - Do use a
get-only property for a value calculated from other properties. - Don’t do slow work in a hook. It runs on every read or write.
- Don’t look for
__getor__set. They do not exist. Use hooks orPropertyObserver.
