Patterns For PHP
Index Patterns News Forums

Lazy Initialization

From Patterns For PHP

This is article is a stub. You can help Patterns for PHP by expanding it.

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.

A Simple PHP Example

php
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;
    }
}

A PHP 5 Example

php
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');
    }
}
Retrieved from "/wiki/Lazy_Initialization"
MediaWiki
GNU Free Documentation License 1.2