Skip to content
This repository has been archived by the owner on May 7, 2021. It is now read-only.

替换自带缓存系统 #94

Open
jackwangshukai opened this issue Dec 11, 2020 · 0 comments
Open

替换自带缓存系统 #94

jackwangshukai opened this issue Dec 11, 2020 · 0 comments

Comments

@jackwangshukai
Copy link

jackwangshukai commented Dec 11, 2020

如何替换easydingtalk自带的缓存。使用redis替代 目前我的做法是修改包里的代码 把缓存那边获取改了参照 easyWeChat改的
代码如下
`namespace EasyDingTalk\Kernel\Concerns;

use Psr\Cache\CacheItemPoolInterface;
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;
use Symfony\Component\Cache\Simple\FilesystemCache;
use Psr\SimpleCache\CacheInterface as SimpleCacheInterface;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;

trait InteractsWithCache
{
/**
* @var \Psr\SimpleCache\CacheInterface
*/
protected $cache;

/**
 * @return \Psr\SimpleCache\CacheInterface
 * @throws InvalidArgumentException
 */
public function getCache()
{
    if ($this->cache) {
        return $this->cache;
    }
    if (property_exists($this, 'app') && isset($this->app['cache'])) {
        $this->setCache($this->app['cache']);

        // Fix PHPStan error
        assert($this->cache instanceof \Psr\SimpleCache\CacheInterface);

        return $this->cache;
    }

    return $this->cache = $this->createDefaultCache();
}

/**
 * Set cache instance.
 *
 * @param \Psr\SimpleCache\CacheInterface|\Psr\Cache\CacheItemPoolInterface $cache
 *
 * @return $this
 *
 * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
 */
public function setCache($cache)
{
    if (empty(\array_intersect([SimpleCacheInterface::class, CacheItemPoolInterface::class], \class_implements($cache)))) {
        throw new InvalidArgumentException(\sprintf('The cache instance must implements %s or %s interface.', SimpleCacheInterface::class, CacheItemPoolInterface::class));
    }

    if ($cache instanceof CacheItemPoolInterface) {
        if (!$this->isSymfony43()) {
            throw new InvalidArgumentException(sprintf('The cache instance must implements %s', SimpleCacheInterface::class));
        }
        $cache = new Psr16Cache($cache);
    }

    $this->cache = $cache;

    return $this;
}

/**
 * @return \Psr\SimpleCache\CacheInterface
 */
protected function createDefaultCache()
{
    if (class_exists(Psr16Cache::class)) {
        return new Psr16Cache(new FilesystemAdapter('easydingtalk'));
    }

    return new FilesystemCache('easydingtalk');
}

/**
 * @return bool
 */
protected function isSymfony43(): bool
{
    return \class_exists('Symfony\Component\Cache\Psr16Cache');
}

}`

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant