xtain/psr6-null

PSR-6 缓存 NullObject 实现,用于避免 null 检查和测试

3.0.0 2022-01-19 18:17 UTC

This package is auto-updated.

Last update: 2024-09-20 00:00:52 UTC


README

缺失的 PSR-6 NullObject 实现。

当你想

  • 避免使用 null 检查逻辑时,请阅读更多内容 这里
  • 需要为测试创建一个假的缓存实现

安装

composer require xtain/psr6-null

示例 / 使用方法

在此包之前,如果你想避免对特定 PSR-6 缓存实现 的包依赖,需要允许 null 作为参数

旧代码

namespace MyPackage;

use Psr\Cache\CacheItemPoolInterface;

class MyCode
{

    public function setCache(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 XTAIN\Psr\Cache\NullCacheItemPool;
use XTAIN\Psr\Cache\CacheItemPoolAwareInterface;
use XTAIN\Psr\Cache\CacheItemPoolAwareTrait;

class MyCode implements CacheItemPoolAwareInterface
{
    use CacheItemPoolAwareTrait;

    /**
     * You could require a cache instance, so you can remove the null check in __construct() as well
     */
    public function __construct()
    {
        $this->cache = new NullCacheItemPool();
    }

    /**
     * @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;
    }
}