Skip to content

Instantly share code, notes, and snippets.

@bpiel
Created January 3, 2012 17:12
Show Gist options
  • Save bpiel/1555855 to your computer and use it in GitHub Desktop.
Save bpiel/1555855 to your computer and use it in GitHub Desktop.
simple general PHP lazy loader
<?php
$chart = $chartMapper->getChartById($chartId);
$user = $chart->getUser();
$client = $chart->getClient();
$trend = $chart->getTrend();
?>
<?php
$chart = $chartMapper->getChartById($chartId);
$user = $userMapper->getUserByChartId($chartId);
$client = $clientMapper->getClientByChartId($chartId);
$trend = $trendMapper->getTrendByChartId($chartId);
?>
<?php
class Chart{
private $id;
private $name;
private $lazyLoadedUser;
public function __construct($id, $name){
$this->id = $id;
$this->name = $name;
}
public function setName($name){
return $this->name = $name;
}
public function getName(){
return $this->name;
}
public function setUser($userOrProvider){
$this->lazyLoadedUser = new LazyLoader($userOrProvider);
}
public function getUser(){
return call_user_func($this->lazyLoadedUser);
}
}
?>
<?php
class ChartMapper{
public function getChart($chartId){
... sql sql sql ...
$chart = new Chart(...);
$chart->setUser(
function() use ($chartId, $userMapper){
return $userMapper->getUserByChartId($chartId);
}
);
return $chart;
}
}
?>
<?php
class LazyLoader{
private $providerOrValue;
private $evaluated = false;
public function __construct($providerOrValue) {
$this->providerOrValue = $providerOrValue;
}
public function __invoke(){
if (!$this->evaluated){
if (is_callable($this->providerOrValue))
$this->providerOrValue = call_user_func ($this->providerOrValue);
$this->evaluated = true;
}
return $this->providerOrValue;
}
}
?>
<?php
$otherUsersOnSameClient = $chart->getClient()->getAllUsers();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment