rodrigovr/php-aop-cache

使用面向切面编程技术缓存方法调用。

dev-master 2021-09-06 23:08 UTC

This package is not auto-updated.

Last update: 2024-10-01 17:27:00 UTC


README

使用 Runkit7 实现方法调用的面向切面缓存

目标

该项目允许您使用缓存行为装饰方法调用。换句话说,这意味着您可以在不修改外部类源代码的情况下,“插入”一个缓存机制到选定的公共方法中。

何时使用它?

  1. 在重构大型代码库之前。
  2. 处理第三方代码时。
  3. 避免许可问题。
  4. 避免重复代码。
  5. 轻松测试缓存后端。

这不是一个完整的列表,只是一些启示!

依赖关系

  • 安装并启用runkit7
  • php 7.2+

可以缓存什么?

您必须仅装饰用户定义的方法。不支持原生类。

示例:您不能直接附加到 PDO::query。

如何使用?

  1. 使用 composer 安装:composer require rodrigovr/php-aop-cache

  2. 尽快,使用给定的缓存实现实例化装饰器

use rodrigovr\Aop;

...

$decorator = Cache\Decorator::create(new Cache\MemoryCache);
  1. 将装饰器附加到您想要缓存结果的任何方法
$decorator->attachTo('SomeClass', 'methodName')
          ->attachTo('SomeClass', 'anotherMethodName')
          ->attachTo('AnotherClass', 'oneMoreMethod');
  1. 如果需要,设置结果缓存的时间(以秒为单位)
// cache results up to 5 minutes
$decorator->expires(300);
  1. 您还可以通过大小(以字节为单位)限制缓存项
// results over 10MB will not be saved
$decorator->limit(10000000);
  1. 支持多个装饰器
$applyMemoryCache = Cache\Decorator::create(new Cache\MemoryCache);
$applySessionCache = Cache\Decorator::create(new Cache\SessionCache);
$applyApcuCache = Cache\Decorator::create(new Cache\SessionCache);
  1. 您可以创建自定义缓存后端
use rodrigovr\Aop;

class MyCache implements Cache\Storage {
    public function save($key, $value, $ttl) {
        // your custom save implementation
    }
    public function load($key) {
        // custom load implementation
    }
}

$decorator = Cache\Decorator::create(new MyCache)->expires(120);