Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Lazyloading resources from the Zend Framework bootstrap

View Bootstrap.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
<?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;
};
}
}
Owner
androa commented

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.