Skip to content

Instantly share code, notes, and snippets.

@laocoi
Forked from md2perpe/lazyload.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/9f78fca9c200e501e65eeeab324c60f5 to your computer and use it in GitHub Desktop.
Save laocoi/9f78fca9c200e501e65eeeab324c60f5 to your computer and use it in GitHub Desktop.
Lazyloading in PHP
<?php
abstract class Loader
{
abstract public function load();
}
class PaymentLoader extends Loader
{
protected $id;
public function __construct($id) { $this->id = $id; }
public function load()
{
if ($this->id == 123)
{
return array(
'amount' => 100,
'customer' => CustomerRepository::findById(5),
);
}
}
}
class CustomerLoader extends Loader
{
protected $id;
public function __construct($id) { $this->id = $id; }
public function load()
{
if ($this->id == 5)
{
return array(
'id' => 5,
'name' => 'John Doe',
);
}
}
}
class LazyObject
{
protected $fields;
protected $loader;
public function __get($field)
{
if (!isset($this->fields) && isset($this->loader))
{
$this->fields = $this->loader->load();
}
return $this->fields[$field];
}
public function setLoader(Loader $loader)
{
$this->loader = $loader;
}
}
class Customer extends LazyObject
{
}
class Payment extends LazyObject
{
}
class PaymentRepository
{
public static function findById($id)
{
$payment = new Payment;
$payment->setLoader(new PaymentLoader($id));
return $payment;
}
}
class CustomerRepository
{
public static function findById($id)
{
$customer = new Customer;
$customer->setLoader(new CustomerLoader($id));
return $customer;
}
}
function pre($x)
{
echo '<pre>';
print_r($x);
echo '</pre>';
}
$payment = PaymentRepository::findById(123);
pre($payment);
echo 'Amount: ', $payment->amount, '<br>';
pre($payment);
echo 'Customer name: ', $payment->customer->name, '<br>';
pre($payment);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment