Created
June 27, 2011 18:55
-
-
Save md2perpe/1049509 to your computer and use it in GitHub Desktop.
Lazyloading in PHP
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 | |
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
This was a response to https://gist.github.com/1046613