Revocable objects
Some objects stop being valid while the program runs. A row that was deleted from the database is
one example. A class that implements Revocable gets the method revoke(). To revoke an object
means to tell the program that the object is no longer valid. After that, every use of the object
throws an error. Passing, storing and comparing it with == do not throw.
Revocable objects
Revocable is the interface for an object that can stop being valid, such as a deleted database row.
To revoke an object means to tell the program that the object is no longer valid. A class that implements Revocable gets two methods. revoke() revokes the object, and a second call does nothing. isRevoked() returns true after revoke() was called.
After revoke(), every Core\ObjectMap, Core\ObjectSet and Core\Heap removes the object immediately. Their count() is correct, and a running foreach skips it.
A plain array, a property or a variable still contains the object. Every use of a revoked object throws RevokedObjectError, such as a property read, a method call or a conversion to a string. The message names the class and the line of the first revoke(). ==, is, ::class and passing or storing the object do not throw.
Good to know: only a class with no parent class can write implements Revocable. All its subclasses are then revocable too.
The examples below show an identity map that forgets a deleted row, a set of online users, and a job heap.
An identity map forgets a deleted row
<?nvs// Shows a map of loaded posts that removes a post as soon as the program deletes it.
abstract class Storable implements Revocable{ public function constructor(public int $id) {}
// `delete` revokes the object. Every `Core\ObjectMap` that contains it removes it. public function delete(): void { $this->revoke(); }}
final class Post extends Storable{ public function constructor(int $id, public string $title) { parent::constructor($id); }}
final class IdentityMap{ // A static property cannot have a `new` object as its default value. // So `all()` creates the map the first time it is called. private static ?Core\ObjectMap<string, Storable> $objectsByKey = null;
public static function all(): Core\ObjectMap<string, Storable> { return self::$objectsByKey ??= new Core\ObjectMap<string, Storable>(); }
public static function remember(Storable $object): void { self::all()->set("{$object::class}#{$object->id}", $object); }}
var $hello = new Post(1, 'Hello');var $news = new Post(2, 'News');var $later = new Post(3, 'Later');IdentityMap::remember($hello);IdentityMap::remember($news);IdentityMap::remember($later);
// The map has three posts. This prints 3.echo IdentityMap::all()->count(), "\n";
// After `delete`, the map no longer contains post 2. This prints 2.$news->delete();var $map = IdentityMap::all();echo $map->count(), "\n";
// The loop prints only the posts that were not deleted.foreach ($map as string $key => Storable $object) { echo $key, "\n";}32Post#1Post#3A set of online users
<?nvs// Shows a set of online users that loses a user as soon as the user logs out.
final class User implements Revocable{ public function constructor(public string $name) {}
// `logOut` revokes the user. Every `Core\ObjectSet` that contains the user removes it. public function logOut(): void { $this->revoke(); }}
var $ada = new User('ada');var $bob = new User('bob');var $eve = new User('eve');
var $online = new Core\ObjectSet<User>();$online->add($ada);$online->add($bob);$online->add($eve);
// Three users are online. This prints 3.echo $online->count(), "\n";
// `bob` logs out and leaves the set. This prints 2.$bob->logOut();echo $online->count(), "\n";
// The loop prints `ada` and `eve`.foreach ($online as User $user) { echo $user->name, "\n";}
// `bob` is revoked, so `$online->add($bob)` does nothing. This prints 2 again.$online->add($bob);echo $online->count(), "\n";32adaeve2A job heap skips a cancelled job
<?nvs// Shows a job queue where a cancelled job is never run.
final class Job implements Revocable, Comparable{ public function constructor(public string $name, public int $priority) {}
// The heap returns the job with the smallest `priority` first. public function compareTo(Job $other): int { return $this->priority - $other->priority; }
// `cancel` revokes the job. Every `Core\Heap` that contains it removes it. public function cancel(): void { $this->revoke(); }}
var $email = new Job('send email', 1);var $report = new Job('build report', 2);var $backup = new Job('backup', 3);
var $queue = new Core\Heap<Job>();$queue->push($backup);$queue->push($report);$queue->push($email);
// The email job is cancelled. The queue now has two jobs, so this prints 2.$email->cancel();echo $queue->count(), "\n";
// The cancelled job is no longer in the heap. `pop` returns the two other jobs.// This prints `build report`, then `backup`.while (!$queue->isEmpty()) { var $job = $queue->pop(); echo $job->name, "\n";}2build reportbackupDetails
If a class has a parent class and writes implements Revocable, the compiler reports the error E1001. The help of the error names the top class of the hierarchy, the one with no parent. Write implements Revocable on that class instead. An interface that extends Revocable is the error E1002. A class that declares its own revoke() or isRevoked() is the error E1003. An abstract class with no parent may implement Revocable.
Every use of a revoked object throws RevokedObjectError. RevokedObjectError is a LogicError. These uses throw:
- a property read or write,
.=,+=,++and--on a property, andisset,emptyandisinitof a property; - an
inoutproperty argument, before the call and again when the value is written back; - a method call,
?->included, and astaticmethod that you call through the object; - a method that the class delegates to a property, and a call of a method reference;
- a conversion to a string, such as a variable inside a double-quoted string, a concatenation or
echo; <,<=,>,>=and<=>, which callcompareTo;- a
foreachover the object; clone,Core\Json::encode, and aCore\Reflectread, call or write.
These do not throw: isRevoked(), a second revoke(), and passing, storing or returning the object. yield, creating a method reference, ==, match and switch do not throw either. The type test is, as to a type the object has, and ::class do not throw.
The error message has this form: "This Blog\Post object was revoked in src/Blog/Post.nvs on line 42. A revoked object cannot be used." A second revoke() does not change the line. A call of revoke() through mixed or Core\Reflect has no line in the source code. Then the message names only the class.
Core\Serialize::encode of a revoked object throws too. So does sending it to a task or storing it in a cache. Each of these throws the same error class as for any other value that it cannot copy. The message is the message of RevokedObjectError.
Core\Debug::dump does not throw. It prints the class name and (revoked), and no properties. For an object that is not revoked, it prints the properties of the class and nothing else.
In this section, a collection is a Core\ObjectMap, a Core\ObjectSet or a Core\Heap.
clone of an object that is not revoked gives a new object. The new object is not revoked. It is in no collection, even when the original object is. Core\Serialize::decode also gives a new object that is in no collection.
set, add and push of a revoked object do nothing. So a collection never contains a revoked object. When the memory limit stops a set, add or push, the object is not added to that collection. If the object is revoked later, revoke() works as usual.
Core\ObjectMap<string, Post> is not a Core\ObjectMap<string, Storable>, even when Post extends Storable. If it were, a program could add a Storable that is not a Post to a map of posts.
A static property cannot have a new object as its default value (E0472). Give the property a nullable type, and create the map the first time you need it: self::$objectsByKey ??= new Core\ObjectMap<string, Storable>();
Speed and memory. A property read or a method call through a revocable class, an interface or mixed runs one extra check. Through any other class type there is no check. Each revocable object uses 16 more bytes. The first time it is added to a collection, it uses 24 more bytes. Each collection that contains it adds another 32 bytes. revoke() takes longer when more collections contain the object. The size of each collection does not change its speed. The memory belongs to the request and is freed when the request ends.
What happens after revoke()
Section titled “What happens after revoke()”| You write | The result |
|---|---|
$post->revoke() |
the object is removed from every Core\ObjectMap, Core\ObjectSet and Core\Heap |
$post->isRevoked() |
true |
$post->title, $post->title = 'x' |
throws RevokedObjectError |
$post->title .= '!', isinit($post->title), bump(inout $post->views) |
throws RevokedObjectError |
$post->publish(), $post?->publish(), a static method called as $post->make() |
throws RevokedObjectError |
$publish = $post->publish(...) |
no error |
$publish() |
throws RevokedObjectError |
"Title: {$post}", echo $post, 'x' . $post |
throws RevokedObjectError |
$post < $other, $post <=> $other |
throws RevokedObjectError |
foreach ($post as $line) |
throws RevokedObjectError |
| a method the class delegates to a property | throws RevokedObjectError |
clone $post, Core\Json::encode($post) |
throws RevokedObjectError |
a Core\Reflect read, call or write |
throws RevokedObjectError |
$post == $other, $post is Post, $post::class |
no error |
$post->revoke() again |
nothing happens |
A plain array, a property or a variable still contains the object. Only Core\ObjectMap,
Core\ObjectSet and Core\Heap remove it. RevokedObjectError is a LogicError. The page
Error types lists it with the other error classes.
Do and don’t
Section titled “Do and don’t”- Do write
implements Revocableon the class with no parent class. All its subclasses are then revocable too. - Do keep objects that can be deleted in a
Core\ObjectMapor aCore\ObjectSet. Then a deleted one is removed immediately. - Do call
isRevoked()when an object may already be revoked. It never throws. - Don’t declare
revoke()orisRevoked()in your class.Revocableprovides both. - Don’t expect a plain array to remove a revoked object. Remove it yourself, or use a
Corecollection.
