nerd / glue
Glue is a simple library that helps various libraries work together, simplifying things like relying on various implementations of things like Caching, by creating a centralized factory for creating such objects. It's a form of Dependency Injection.
This package is auto-updated.
Last update: 2024-11-29 04:46:43 UTC
README
Glue is a simple PHP library that helps various libraries work together with less effort. It primarily provides a centralized factory method for fetching functionality based on an interface definition. For example; if your library can utilize caching, you would could easily obtain the cache-interface by simply calling:
$cache = \Nerd\Glue::get(Psr\Cache\CachePoolInterface::class);
You are now guaranteed that $cache is a class that implements the Psr\Cache\CachePoolInterface
and that you can use it as you wish.
Example 1: Database access
If your library needs access to the database, you could very conveniently do the following:
$db = \Nerd\Glue::get(\PDO::class);
This would provide you with a PDO object, as per the applications configuration. The framework would previosuly have to ave done the following:
\Nerd\Glue::singletonFactory(\PDO::class, function() {
return new PDO("your-connection-string", "user", "pass");
});
Example 2: Caching
$cache = \Nerd\Glue::get(\Psr\Cache\CachePoolInterface);
$item = $cache->getItem("some-cache-key");
if(!$item->exists()) {
// Let's generate the item
$value = "Some string".time();
$item->set($value);
$item->setExpiration(30);
$cache->save($item);
} else {
$value = $item->get();
}
Standardized interfaces
It's recommended that you request interfaces that have been standardized through the process at www.php-fig.org, or standard PHP interfaces. This means that the following is good candidates:
- Psr\Log\LoggerInterface
- Psr\Cache\CachePoolInterface
- Psr\Http\Message\ResponseInterface
- PDO
Dependency Injection Container
There is a very interesting proposal draft related to dependency injection at https://github.com/container-interop/fig-standards/blob/master/proposed/container.md. Dependency injection basically does what Glue does, in a more elaborate way. Interestingly, Glue still has a purpose in this case, as you need a way to retrieve the Dependency Injection container:
$container = \Nerd\Glue::get(\Psr\Container\ContainerInterface::class);
Also, if this proposal is approved - Glue will naturally integrate with the configured Dependency Injection Container.