PHP 8.4 lazy ghosts: load objects only when read
I had a listing page that took a list of product IDs, built a Product object for each one, and then only rendered the first twelve. Every object had already paid for its database row or API call in the constructor, so about eighty percent of that work was thrown away. PHP 8.4 gives me a clean fix for this without a proxy library: native lazy objects.
The idea: a ghost that knows its ID
ReflectionClass::newLazyGhost() creates an instance of your own class without calling the constructor. The initializer you pass runs the first time the object's state is observed or modified. According to the manual page, the initializer receives the object, is no longer lazy at that point, and must return nothing. That means I can call the constructor from inside it.
The one thing I want to read for free is the ID, because I already have it. ReflectionProperty::skipLazyInitialization() marks a single property as initialized-on-its-own, so reading or setting it does not trigger the load.
<?php
declare(strict_types=1);
final class Product
{
public function __construct(
public int $id,
public string $name,
public float $price,
) {
}
}
final class LazyProductFactory
{
/**
* @param \Closure(int): array{name: string, price: string|float} $fetchRow
*/
public function __construct(private readonly \Closure $fetchRow)
{
}
public function reference(int $id): Product
{
$reflector = new \ReflectionClass(Product::class);
$product = $reflector->newLazyGhost(
function (Product $product) use ($id): void {
$row = ($this->fetchRow)($id);
$product->__construct($id, $row['name'], (float) $row['price']);
}
);
// The ID is already known, so reading it must not hit the database.
$idProperty = $reflector->getProperty('id');
$idProperty->skipLazyInitialization($product);
$idProperty->setValue($product, $id);
return $product;
}
}
Using it, and checking what actually loaded
The factory takes any closure that fetches one row, so in Drupal it can wrap a database query and in Symfony it can wrap an HttpClient call. Building the list is now cheap, and only the objects I touch cost anything:
<?php
$factory = new LazyProductFactory(function (int $id): array {
// Imagine a slow query or HTTP call here.
return ['name' => "Product $id", 'price' => '19.90'];
});
$products = array_map($factory->reference(...), range(1, 80));
foreach (array_slice($products, 0, 12) as $product) {
echo $product->id, ': ', $product->name, PHP_EOL; // name triggers the load
}
$reflector = new \ReflectionClass(Product::class);
$untouched = array_filter(
$products,
fn (Product $p): bool => $reflector->isUninitializedLazyObject($p)
);
echo count($untouched), ' products never loaded', PHP_EOL;
Tracing it by hand: the first twelve have their name read, so each runs its initializer once. The other sixty-eight never do, and isUninitializedLazyObject() should report them as still lazy. I traced this against the documented behavior rather than running it, so run it once on 8.4 before trusting my claim.
Gotchas I would watch for
- The constructor is skipped. If you forget to call it inside the initializer, you get an object with uninitialized typed properties and an
Erroron first read. - Almost everything triggers loading. Per the lazy objects docs, property reads and writes,
isset(),get_object_vars(),foreach,json_encode(),serialize()and cloning all initialize the object. A strayjson_encode($products)loads all eighty. - Exceptions roll back. If the initializer throws, the object goes back to lazy, so a retry is possible. Side effects on other objects are not reverted.
- User classes only. Internal classes, apart from
stdClass, throw anError.
I would reach for this when the expensive part is real and the usage is sparse, like list pages, relation graphs, or DI wiring. I would not bother for cheap objects: the reflection setup costs something, and an N+1 query problem is better solved with one batched query than by hiding it behind lazy loading. If you can batch, batch first.