alielmajdaoui/laravel-memoize

将昂贵的计算值缓存,以便在每次请求的不同组件中使用。

0.0.1 2021-03-21 16:59 UTC

This package is auto-updated.

Last update: 2024-09-29 05:49:50 UTC


README

将昂贵的计算值缓存,以便在每次请求的不同组件中使用。

用例

假设你有一个 AddCommentRequest 类,其任务是验证添加到你的博客文章中的评论。

在验证过程中,你可能需要使用 Eloquent 模型或直接使用 DB 门面进行数据库查询,而这个查询结果可能在未来的另一个应用程序组件中需要,比如在你的 CommentController 中,这个请求类(被注入)被调用。

如果你在这两个不同的地方执行相同的查询,你将会有重复的查询,这就是 laravel-memoize 走出来拯救你的地方。它很简单,只需要将查询包装在一个 \Closure 中,它就会为你缓存。

安装

使用 composer 安装

composer require aliem/laravel-memoize

用法

你可以通过使用来自 Aliem\Memoize\Facades\Memoize 门面的方法 remember(string $key, \Closure $callback) 来缓存一个重量级的计算值。

示例

<?php

namespace App\Controllers;

use Aliem\Memoize\Facades\Memoize;

class MyAwesomeController extends Controller {
    public function index() {
        
        // Check if the item `iam_heavy` is memoized and return it,
        // otherwise, run the \Closure and memoize the result.
        $value = Memoize::remember('iam_heavy', function() {
            $result = 0;

            for ($i = 0; $i < 1000000; $i++) {
                $result += $i * rand(1, 10);
            }

            return $result;
        });

        return response(sprintf("My memoized value: %s", $value));
    }
}

remember(string $key, \Closure $callback): mixed

检查项目是否已缓存,如果没有,则执行 \Closure 并缓存结果。

Memoize::remember(string $key, \Closure $callback);

示例

<?php

use Aliem\Memoize\Facades\Memoize;

$comment = Memoize::remember('comment:1', function() {
    return Comment::find(1);
});

get(string $key): mixed

获取一个已缓存的项目

Memoize::get(string $key);

示例

<?php

use Aliem\Memoize\Facades\Memoize;

$comment = Memoize::get('comment:1');

put(string $key, mixed $value): void

缓存一个项目

<?php

use Aliem\Memoize\Facades\Memoize;

$result = Comment::find(1);
$comment = Memoize::put('comment:1', $result);

has(string $key): bool

检查一个项目是否已缓存

<?php

use Aliem\Memoize\Facades\Memoize;

if (Memoize::has('comment:1')) {
    echo 'the item `comment:1` is memoized';
}

forget(string $key): bool

删除一个已缓存的项目。

<?php

use Aliem\Memoize\Facades\Memoize;

Memoize::forget('comment:1');

Memoize::flush()

删除所有已缓存的项目

<?php

use Aliem\Memoize\Facades\Memoize;

Memoize::flush();

许可证

MIT.