PHP code example of groupbuy / hyperf-memory-cache

1. Go to this page and download the library: Download groupbuy/hyperf-memory-cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

groupbuy / hyperf-memory-cache example snippets


use Groupbuy\HyperfMemoryCache\Annotation\MemoryCache;

class ConfigService
{
    #[MemoryCache(key: 'cfg:{sid}:{column}', ttl: 30)]
    public function getConfig(string $sid, string $column): array
    {
        return Db::table('shop_config')->where(...)->get()->toArray();
    }
}

use Groupbuy\HyperfMemoryCache\Annotation\MemoryCacheEvict;

class ConfigService
{
    #[MemoryCacheEvict(key: 'cfg:{sid}:{column}')]
    public function setConfig(string $sid, string $column, array $cfg): void
    {
        Db::table('shop_config')->where(...)->update($cfg);
    }
}

// config/autoload/memory_cache.php
return [
    'enabled' => (bool) env('MEMORY_CACHE_ENABLE', false),
    'tables'  => [
        'default' => [
            'table_name'          => 'memory_cache',
            'table_size'          => (int) env('MEMORY_CACHE_TABLE_SIZE', 16384),
            'max_value_bytes'     => 3500,
            'conflict_proportion' => 0.2,
        ],
        'goods' => [
            'table_name'          => 'memory_cache_goods',
            'table_size'          => (int) env('MEMORY_CACHE_GOODS_TABLE_SIZE', 4096),
            'max_value_bytes'     => 6000,
            'conflict_proportion' => 0.2,
        ],
    ],
    // ... 其他全局配置
];

#[MemoryCache(key: 'goods:{id}', channel: 'goods', ttl: 30)]
public function getGoodsDetail(string $id): array { ... }

#[MemoryCacheEvict(key: 'goods:{id}', channel: 'goods')]
public function updateGoodsDetail(string $id, array $data): void { ... }

$value = $this->manager->remember(
    'goods:123',
    fn () => $this->repository->getGoodsDetail('123'),
    ttl: 30,
    channel: 'goods',
);

#[MemoryCache(key: 'shop:{sid}:cfg:{column}', ttl: 60)]
public function getShopConfig(string $sid, string $column): array { ... }
// 调用 getShopConfig('S001', 'theme') → key = "shop:S001:cfg:theme"

use Groupbuy\HyperfMemoryCache\Cache\Memory\MemoryCacheManager;

// 默认 channel
$value = $this->manager->remember(
    'shop:S001:cfg:theme',
    fn () => $this->repository->getConfig('S001', 'theme'),
    ttl: 30,
    cacheNull: true,
    singleFlight: true,
    jitter: true,
);

// 指定 channel
$value = $this->manager->remember(
    'goods:123',
    fn () => $this->repository->getGoodsDetail('123'),
    ttl: 30,
    channel: 'goods',
);
bash
php bin/hyperf.php vendor:publish groupbuy/hyperf-memory-cache
bash
php bin/hyperf.php memory-cache:stats