Skip to content

Instantly share code, notes, and snippets.

@beberlei
Last active November 12, 2019 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beberlei/712f48fcf6e1db9a793effbba1ad9686 to your computer and use it in GitHub Desktop.
Save beberlei/712f48fcf6e1db9a793effbba1ad9686 to your computer and use it in GitHub Desktop.
<?php
class User
{
public $id;
public $username;
public $email;
}
$user = new User();
$user->id = 1234;
register_lazy_listener($user, ['username', 'email], function ($object, $lazyProperties, $accessedProperty) {
$sql = 'SELECT username, email FROM user WHERE id = ?';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(1, $object->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// $row with {"username": "user1234", ..."} for id: 1234
$object->username = $row['username'];
$object->email = $row['email'];
return LAZY_UNREGISTER; // LAZY_KEEP? or always unregister when accessed?
});
echo $user->username; // makes magic sql query and prints "user1234"
echo $user->email; // no magic anymore here, the property is initialized
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment