public
Created

Lazyloading resources from the Zend Framework bootstrap

  • Download Gist
Bootstrap.php
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;
};
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.