Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
class User { protected $_id; public function getId() { return $this->_id; } } class Post { protected $_userId; protected $_text; /** * * @var User */ protected $_user; public function setUser(User $user) { $this->_userId = $user->getId(); $this->_user = $user; } public function getUser() { if (!$this->_user) { $this->_user = new User($this->_userId); } return $this->_user; } public function setText($text) { $this->_text = $text; } public function getText() { return $this->_text; } }
class View { protected $_values = array(); public function set($name, $value) { $this->_values[$name] = $value; } public function render($file) { extract($this->_values); ob_start(); include($file); return ob_get_clean(); } } class Page { /** * View object. * * @var View */ protected $_view; public function __construct() { // remove attribute to use the __get magic method in first access unset($this->_view); } public function __get($name) { if ($name == '_view') { // load view object $this->_view = new View(); return $this->_view; } } public function actionIndex() { $this->_view->set('title', 'Lazy Initialization'); print $this->_view->render('lazy.tpl'); } }