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

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

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');
    }
}

 
lazy_initialization.txt · Last modified: 2010/05/18 02:06 by mfacenet
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki