Skip to content

Instantly share code, notes, and snippets.

@androa
Created May 31, 2012 12:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save androa/2843053 to your computer and use it in GitHub Desktop.
Save androa/2843053 to your computer and use it in GitHub Desktop.
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
Copy link
Author

androa commented Jun 1, 2012

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