thadafinser / psr6-null-cache
PSR-6 缓存 NullObject 实现,用于避免空值检查以及测试
v0.1.0
2016-02-26 14:36 UTC
Requires
- php: ~7.0
- psr/cache: ^1.0
Requires (Dev)
- fabpot/php-cs-fixer: ^1.11
- phpunit/phpunit: ^5.2
This package is not auto-updated.
Last update: 2024-09-14 18:42:15 UTC
README
缺失的 PSR-6 NullObject 实现。
当您想
- 避免使用
null
检查逻辑时,您可以使用此包,更多信息请参阅 此处 - 需要用于测试的模拟缓存实现
安装
composer require thadafinser/psr6-null-cache
示例 / 使用方法
在此包之前,如果您想避免对特定 PSR-6 缓存实现
的依赖,则需要允许参数为 null
旧代码
namespace MyPackage; use Psr\Cache\CacheItemPoolInterface; class MyCode { public function __construct(CacheItemPoolInterface $cache = null) { $this->cache = $cache; } /** * Can return an instance of null, which is bad! * * @return null CacheItemPoolInterface */ public function getCache() { return $this->cache; } private function internalHeavyMethod() { $cacheKey = 'myKey'; // you need to check first, if there is a cache instance around if ($this->getCache() !== null && $this->getCache()->hasItem($cacheKey) === true) { // cache is available + it has a cache hit! return $this->getCache()->getItem($cacheKey); } $result = do_something_heavy(); // you need to check first, if there is a cache instance around if ($this->getCache() !== null) { $item = $this->getCache()->getItem($cacheKey); $item->set($result); $this->getCache()->save($item); } return $result; } }
新代码
namespace MyPackage; use Psr\Cache\CacheItemPoolInterface; use Psr6NullCache\NullCacheItemPool; class MyCode { /** * You could require a cache instance, so you can remove the null check in __construct() as well * * @param CacheItemPoolInterface $cache */ public function __construct(CacheItemPoolInterface $cache = null) { if($cache === null){ $cache = new NullCacheItemPool(); } $this->cache = $cache; } /** * @return CacheItemPoolInterface */ public function getCache() { return $this->cache; } private function internalHeavyMethod() { $cacheKey = 'myKey'; if ($this->getCache()->hasItem($cacheKey) === true) { // cache is available + it has a cache hit! return $this->getCache()->getItem($cacheKey); } $result = do_something_heavy(); $item = $this->getCache()->getItem($cacheKey); $item->set($result); $this->getCache()->save($item); return $result; } }