Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Lazyloading resources from the Zend Framework bootstrap
<?php
/**
* Example Zend Framework bootstrap with lazyloading of resources
*
* @author André Roaldseth <andrer@vg.no>
*/
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
/**
* Creates a lazyloaded Memcached instance
*
* @return Memcached
*/
public function _initMemcached() {
return $this->lazyload(function() {
return new Memcached();
});
}
/**
* Create a lazyloaded PDO instance.
*
* @return PDO
*/
public function _initSomePDOClient() {
$config = $this->getOption('pdo');
return $this->lazyload(function() use ($config) {
return new PDO($config['dsn']);
});
}
/**
* Retrieve a resource from the container.
*
* If the requested resource is a callable it will be exectued and the
* result from the callable is returned instead of the callable itself.
*
* @see Zend_Application_Bootstrap_BootstrapAbstract::getResource()
*/
public function getResource($name) {
$resource = parent::getResource($name);
if (is_callable($resource)) {
return $resource();
} else if ($resource !== null) {
return $resource;
}
}
/**
* Method for creating closures which lazyload the resource.
*
* Creates an closure which will create the resource when called
* and caches this resource so only one instance is created.
*
* @param callback $callable Callback which is able to create the resource.
* @return mixed The instantiated resource, usually an object.
*/
private function lazyload($callable) {
return function () use ($callable) {
static $object;
if (is_null($object)) {
$object = $callable();
}
return $object;
};
}
}
@androa
Owner

Wrote a blog post about how to use this lazy loading: http://tech.vg.no/2012/06/01/lazy-loading-resources-with-zend-framework-bootstrap/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.