Forget a deleted row
A request often reads the same row more than once. This program loads each post once and keeps it
in a Core\ObjectMap. When the program deletes a post, the map removes it immediately.
<?nvs// This program keeps each loaded post in memory, and forgets a post when it is deleted.final class Post implements Revocable{ public function constructor(public int $id, public string $title) {}}
final class Posts{ private Core\ObjectMap<int, Post> $loaded;
public function constructor() { $this->loaded = new Core\ObjectMap<int, Post>(); }
// Returns the post with this id. Only the first call for an id loads it. public function find(int $id): Post { var $saved = $this->loaded->get($id); if ($saved is Post) { echo "from memory\n"; return $saved; } echo "loaded\n"; // A real program would read the row from a database here. var $post = new Post($id, "Post {$id}"); $this->loaded->set($id, $post); return $post; }
// Deletes the post. `revoke()` also removes it from `$loaded`. public function delete(Post $post): void { // A real program would delete the row here. $post->revoke(); }}
var $posts = new Posts();
// The first call prints `loaded`. The second call prints `from memory`.var $first = $posts->find(7);var $second = $posts->find(7);echo $first == $second ? "the same object\n" : "two objects\n";
// After `delete`, the post is not in memory. The next call prints `loaded` again.$posts->delete($first);var $third = $posts->find(7);echo $third->title, "\n";
// The deleted post cannot be used. This prints `true`.echo $first->isRevoked() ? "true\n" : "false\n";loadedfrom memorythe same objectloadedPost 7truePost implements Revocable, so it has the method revoke(). To revoke an object means to tell
the program that the object is no longer valid. delete calls revoke(). After that call, the post
is removed from every Core\ObjectMap, Core\ObjectSet and Core\Heap that contains it. So the
next find(7) does not return the deleted post. It loads the row again.
The variable $first still contains the deleted post. Reading $first->title now throws
RevokedObjectError. isRevoked() does not throw, so you can check it first.
Read Revocable objects for what throws and what does not.
