把一些相似的类,封装成统一的接口便于调用切换。php适配器模式会定义一个接口,接口中定义需要实现的方法,多个子类去实现这些方法的过程。
优点:如果需要封装一个缓存类,缓存类同时支持redis和memcache,切换使用时只需修改相关配置就能实现切换了,而不需要修改大量的代码。减少代码间的耦合,可以方便增减需要实现的类。
Adapter.php
redis.php
connect(); } protected function connect(): void { $this->redis = new Redis(); $this->redis->connect('127.0.0.1', 6379); } public function get(string $key): string { return $this->redis->get($key); } public function set(string $key, string $value, int $ttl = 3600): int { return $this->redis->setex($key, $ttl, $value); } public function del(string $key): int { return $this->redis->delete($key); } }memcache.php
connect(); } protected function connect(): void { $this->memcache = memcache_connect('127.0.0.1', 11211); } public function get(string $key): string { return $this->memcache->get($key); } public function set(string $key, string $value, int $ttl = 3600): bool { return $this->memcache->setex($key, $value, MEMCACHE_COMPRESSED, $ttl); } public function del(string $key): bool { return $this->memcache->delete($key, 0); } }调用:
$cacheType = 'redis'; // 切换时只需修改这里的配置,其他代码不变。 if ($cacheType == 'redis') { $cache = new RedisAdapter(); } else { $cache = new MemcacheAdapter(); } $cache->get('test'); $cache->set('test', 123, 3600); $cache->del('test');二、适配器模式的应用 tp6中的应用缓存类的具体实现在thinkcachedriver目录中。
class Cache extends Manager implements CacheInterface { protected $namespace = '\think\cache\driver\'; public function get($key, $default = null) { return $this->store()->get($key, $default); } public function set($key, $value, $ttl = null): bool { return $this->store()->set($key, $value, $ttl); } public function delete($key): bool { return $this->store()->delete($key); } // ... }



