Adapter

7/9/2021 OOPPattern

# Description

Adapter is a structural design pattern, which allows incompatible objects to collaborate.

  • Kết nối các object độc lập làm việc với nhau.

# Example

# Code

Xử lí cache (kết hợp abstract factory và adapter)

abstract class AdapterFactory
{
    abstract public function getInstance(): AdapterInterface;
}
1
2
3
4
interface AdapterInterface
{
    public function get(string $key);

    public function set(string $key, $value, $expireAt = null);

    public function has(string $key): bool;
}
1
2
3
4
5
6
7
8
class Cache implements AdapterInterface
{
    private AdapterInterface $adapter;

    public function __construct(AdapterInterface $adapter)
    {
        $this->adapter = $adapter;
    }

    public function getAdapter()
    {
        return $this->adapter;
    }

    public function setAdapter($adapter)
    {
        $this->adapter = $adapter;
    }

    public function get(string $key)
    {
        return $this->adapter->get($key);
    }

    public function set(string $key, $value, $expireAt = null)
    {
        return $this->adapter->set($key, $value, $expireAt);
    }

    public function has(string $key): bool
    {
        return $this->adapter->has($key);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class MemcachedFactory extends AdapterFactory
{
    private string $host;
    private string $port;

    public function __construct(string $host = "localhost", string $port = "11211")
    {
        $this->host = $host;
        $this->port = $port;
    }

    public function getInstance(): AdapterInterface
    {
        return new LibMemcached($this->host, $this->port);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class LibMemcached implements AdapterInterface
{
    private \Memcached $memcache;

    public function __construct(string $host, string $port)
    {
        $this->memcache = $this->getMemcache();
        $this->memcache->addServer($host, $port);
    }

    protected function getMemcache(): \Memcached
    {
        return new \Memcached();
    }

    public function get(string $key)
    {
        return $this->memcache->get($key);
    }

    public function set(string $key, $value, $expireAt = null)
    {
        return $this->memcache->set($key, $value, $expireAt);
    }

    public function has(string $key): bool
    {
        return $this->memcache->get($key);
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  • Dùng Adapter Pattern để liên kết Cache và Memcache.
  • Memcache đang dùng Abstract Factory, nếu sau này maintance hoặc sử dụng 1 driver khác (redis, db, file,..) để dùng lưu cache thì cũng dễ dàng và không cần thay đổi Cache theo AdapterInterface ban đầu.