Skip to content

Instantly share code, notes, and snippets.

@beberlei

beberlei/lazy.php Secret

Last active Nov 12, 2019
Embed
What would you like to do?
<?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
You can’t perform that action at this time.