zalatov/runtime-cache-trait

PHP运行时缓存的Trait。

1.0 2019-03-31 04:10 UTC

This package is not auto-updated.

Last update: 2024-09-24 07:42:32 UTC


README

  1. 无需指定多余的private/protected属性。
  2. 注释/文档既不重复在属性上,也不重复在方法上。
  3. 通过方法封装逻辑,确保在其他地方属性不会被修改。

普通用法

<?php
class Product {
    private $images;

    public function getImages(): array {
        if (null === $this->images) {
            $this->images = [new Image];
        }

        return $this->images;
    }
}

通过RuntimeCacheTrait

<?php
class Product {
    use RuntimeCacheTrait;

    public function getImages(): array {
        return $this->objectRuntimeCache(__METHOD__, function() {
            return [new Image];
        });
    }
}

一个对象/模型的实例

<?php
class Product extends \yii\db\ActiveRecord {
    use RuntimeCacheTrait;

    public static function getModel(string $id): ?self {
        return static::globalRuntimeCache([__METHOD__, $id], function() use ($id) {
            return static::findOne($Id);
        });
    }
}