Created
May 31, 2012 12:25
-
-
Save androa/2843053 to your computer and use it in GitHub Desktop.
Lazyloading resources from the Zend Framework bootstrap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/