栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

php适配器模式

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

php适配器模式

    把一些相似的类,封装成统一的接口便于调用切换。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);
    }
    
    // ...
    
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/2456.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号