Skip to content

Instantly share code, notes, and snippets.

@mathiasverraes
Created May 17, 2011 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mathiasverraes/977230 to your computer and use it in GitHub Desktop.
Save mathiasverraes/977230 to your computer and use it in GitHub Desktop.
Lazy Loading with Closures
<?php
// client code
$customer = $customerRepository->find($id);
$orders = $customer->getOrders();
<?php
class Customer
{
public function getOrders()
{
$ordersData = $this->db->query(/* select orders... */);
$orders = array();)
foreach($ordersdata as $orderdata) {
$orders[] = new Order($orderdata);
}
return $orders;
}
}
<?php
class Customer
{
public function getOrders()
{
return $this->orders;
}
}
class CustomerRepository
{
public function find($id)
{
$customerdata = $this->db->query(/* select customer ...*/);
$customer = new Customer($customerdata);
$ordersdata = $this->db->query(/* select orders ... */);
foreach($ordersdata as $orderdata){
$customer->addOrder(new Order($orderdata));
}
}
}
<?php
class Customer
{
public function setOrdersReference(Closure $ordersReference)
{
$this->ordersReference = $ordersReference;
}
public function getOrders()
{
if(!isset($this->orders)) {
$reference = $this->ordersReference;
$this->orders = $reference();
}
return $this->orders;
}
}
class CustomerRepository
{
public function find($id)
{
$db = $this->db;
$customerdata = $db->query(/* select customer ...*/);
$customer = new Customer($customerdata);
$ordersReference = function($customer) use($id, $db) {
$ordersdata = $db->query(/* select orders ... */);
$orders = array();
foreach($ordersdata as $orderdata) {
$orders[] = new Order($orderdata);
}
return $orders;
};
$customer->setOrderReference($ordersReference);
return $customer;
}
}
@md2perpe
Copy link

md2perpe commented Dec 7, 2012

Aren't you missing a return $orders; in listing4.php?

@mathiasverraes
Copy link
Author

@md2perpe Thanks, fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment