-
-
Save beberlei/712f48fcf6e1db9a793effbba1ad9686 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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