titasgailius/closure-cache

缓存方法、函数或闭包的结果。

1.0 2017-05-05 20:59 UTC

This package is auto-updated.

Last update: 2024-09-12 12:26:19 UTC


README

这是一个简单的PHP缓存机制,用于存储方法、函数或闭包的结果。
它计算闭包的结果一次,并在后续调用中返回。

用法

<?php

use ClosureCache\ClosureCache;

function somethingSlow()
{
    return once(function () {
        // Code...
    });
}

安装

使用composer

$ composer require titasgailius/closure-cache
{
    "require": {
        "titasgailius/closure-cache": "~1.00"
    }
}

示例

之前

<?php

use ClosureCache\ClosureCache;

class SomeClass
{
    public static function think()
    {
        sleep(10);

        return 'It takes some time to process this.';
    }
}

/**
 * 10 seconds to process it.
 */
SomeClass::think();

/**
 * Another 10 seconds to process it
 * which makes it 20 seconds in total.
 */
SomeClass::think();

之后

<?php

use ClosureCache\ClosureCache;

class SomeClass
{
    public static function think()
    {
        return once(function () {
            sleep(10);

            return 'It takes some time to process this.';
        });
    }
}

/**
 * 10 seconds to process
 */
SomeClass::think();

/**
 * ClosureCache detects that this was already
 * processed and returns it from the cache.
 */
SomeClass::think();

ClosureCache对参数敏感

<?php

use ClosureCache\ClosureCache;

class SomeClass
{
    public static function think($message)
    {
        return once(function () use ($message) {
            sleep(10);

            return $message;
        });
    }
}

/**
 * 10 seconds to process
 */
SomeClass::think('foo');

/**
 * Another 10 seconds to process it because
 * different parameters were passed.
 */
SomeClass::think('bar');