Skip to content

Instantly share code, notes, and snippets.

@laocoi
Forked from juzna/example.php
Created June 4, 2018 10:35
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 laocoi/8f01a2d4f55dc02af5029a311bdef1a6 to your computer and use it in GitHub Desktop.
Save laocoi/8f01a2d4f55dc02af5029a311bdef1a6 to your computer and use it in GitHub Desktop.
Lazy-loading for PHP
<?php
class Address {
public $street;
public $town;
}
class Customer {
public $id;
public $name;
public $address;
}
class Payment {
public $amount;
public $customer;
}
$db = getDatabase();
$payment = $db->load('Payment', 123);
/*
$payment containts:
amount = 100;
customer = class Customer {
id = 5;
name = uninitialized;
address = uninitialized;
}
}
*/
echo $payment->customer->name; // DB layer will load customer info
// or
echo $payment->customer->address->town; // DB layer will load customer & address info
<?php
/**
* Example of possible lazy-loading in PHP
* Added new special value called "uninitialized". When a property with this value is being read from object,
* __initialize($propertyName) magic method is invoked to lazy-load the value.
*/
class Foo {
private $bar = uninitialized;
private $lol = "lol";
public $pub = uninitialized;
public $blank = uninitialized;
function getBar() {
echo "Getter method bar, ";
return $this->bar;
}
function getLol() {
echo "Getter method lol, ";
return $this->lol;
}
function getPub() {
echo "Getter method pub, ";
return $this->pub;
}
function __get($name) {
echo "Magic getter $name, ";
return $this->$name;
}
function __initialize($name) {
if($name !== 'blank') {
echo "Initializing $name, ";
$this->$name = "I'm $name";
}
else {
echo "Trying to initialize blank, ";
}
}
function clean() {
$this->bar = $this->lol = $this->pub = uninitialized;
}
}
// __initialize will be called only once, on first access
$foo = new Foo;
var_dump($foo->getBar()); // Getter method bar, Initializing bar, string(7) "I'm bar"
var_dump($foo->getBar()); // Getter method bar, string(7) "I'm bar"
// magic __get is called first, and inside it's initialized
$foo = new Foo;
var_dump($foo->bar); // Magic getter bar, Initializing bar, string(7) "I'm bar"
var_dump($foo->bar); // Magic getter bar, string(7) "I'm bar"
$foo->clean();
var_dump($foo->bar); // Magic getter bar, Initializing bar, string(7) "I'm bar"
var_dump($foo->bar); // Magic getter bar, string(7) "I'm bar"
// lazy-loading of public properties
$foo = new Foo;
var_dump($foo->pub); // Initializing pub, string(7) "I'm pub"
// normal value remains as expected
$foo = new Foo;
var_dump($foo->getLol()); // Getter method lol, string(3) "lol"
// variable which cannot be initialized
$foo = new Foo;
var_dump($foo->blank); // Trying to initialize blank, undefined
var_dump($foo->blank); // Trying to initialize blank, undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment