Wednesday, November 9, 2011

Lazy loading with PHP magic methods

Using some php magic for a dead simple lazy loading framework:
class DemoContext {
    protected $_lazy_vars = array(
        'cache' => null,
        'request' => null,
    );

    # the magic happens here ;)
    public function __get( $varname ) {
        if ( ! array_key_exists( $varname, $this->_lazy_vars ) )
            return null;
        if ( $this->_lazy_vars[ $varname ] !== null )
            return $this->_lazy_vars[ $varname ];

        $value = null;
        switch ( $varname ) {
            case 'cache':
                $value = new \appcore\cache();
            break;
            case 'request':
                $value = new \appcore\request();
            break;
        }
        $this->_lazy_vars[ $varname ] = $value;
        return $value;
    }
}

# using it:
$demo = new DemoContext();
if ( $demo->cache->check() ) {
    # ...
}

if ( $demo->request->hasHeader('Location') ) {
    # ...
}
Using lazy loading is great for setting back of any object creation until you're sure you actually need it. This could be a huge memory improvement in some cases, anywhere where there might be useless object creation.