mardi 10 mars 2020

Apply principle of Stable Abstraction in PHP

Advice from phpMetrics is to make use of the "Stable Abstraction Principle" and listed me some classes.

The classes are very simple and implement PSR SimpleCache.

How do I apply the principle correctly to this class?

use Psr\SimpleCache\CacheInterface;
use stdClass;

class Filecache implements CacheInterface
{
    /**
     * @var stdClass
     */
    protected $obj;

    /**
     * @var string Path to the cache file
     */
    protected $file;

    /**
     * @param string $cacheFile
     */
    public function __construct($cacheFile)
    {
        $this->file = $cacheFile;
        if (!file_exists($this->file)) {
            touch($this->file);
        }
        $this->obj = json_decode(file_get_contents($this->file));
    }

    /**
     *
     */
    public function __destruct()
    {
        $file = fopen($this->file, 'w');
        fwrite($file, json_encode($this->obj));
        fclose($file);
    }

    /**
     * @inheritDoc
     */
    public function get($key, $default = null)
    {
        return isset($this->obj->{$key}) ? $this->obj->{$key} : $default;
    }

    /**
     * @inheritDoc
     */
    public function set($key, $value, $ttl = null)
    {
        if (!$this->obj instanceof stdClass) {
            $this->obj = new stdClass();
        }
        $this->obj->{$key} = $value;
    }

    /**
     * @inheritDoc
     */
    public function delete($key)
    {
        unset($this->obj->{$key});
    }

    /**
     * @inheritDoc
     */
    public function clear()
    {
        $this->obj = new stdClass();
        return true;
    }

    /**
     * @inheritDoc
     */
    public function getMultiple($keys, $default = null)
    {
        // TODO: Implement getMultiple() method.
    }

    /**
     * @inheritDoc
     */
    public function setMultiple($values, $ttl = null)
    {
        // TODO: Implement setMultiple() method.
    }

    /**
     * @inheritDoc
     */
    public function deleteMultiple($keys)
    {
        // TODO: Implement deleteMultiple() method.
    }

    /**
     * @inheritDoc
     */
    public function has($key)
    {
        return isset($this->obj->{$key});
    }
}

Aucun commentaire:

Enregistrer un commentaire