batenburg/cache-bundle

一个简化使用 symfony 缓存的缓存包。

v2.0.7 2021-01-10 12:14 UTC

This package is auto-updated.

Last update: 2024-09-10 20:04:47 UTC


README

Symfony 框架的缓存。

构建状态: 构建状态

什么是缓存包?

缓存包是围绕 Symfony Cache 的一个仓库。其目的是简化 Symfony Cache 的使用。

适用于谁?

此包推荐用于微服务、领域驱动开发或仓库设计模式。此包不适用于与 Doctrine ORM 一起使用。

安装

使用 composer 安装

composer require batenburg/cache-bundle

注册包,在 config/bundles.php 中添加以下行

    Batenburg\CacheBundle\CacheBundle::class => ['all' => true],

使用方法

安装完成后,可以通过依赖注入解析 CacheRepositoryInterface。或者通过容器。强烈建议使用依赖注入。

示例:

<?php

namespace App\Product\Repository;

use Batenburg\CacheBundle\Repository\Contract\CacheRepositoryInterface;
use App\Product\Model\Brand;
use App\Product\Repository\Contract\BrandRepositoryInterface;

class BrandCacheRepository implements BrandRepositoryInterface
{

    const EXPIRES_AFTER_IN_SECONDS = 3600;

    /**
     * @var CacheRepositoryInterface
     */
    private $cacheRepository;

    /**
     * @var BrandRepositoryInterface
     */
    private $brandRepository;

    /**
     * @param CacheRepositoryInterface $cacheRepository
     * @param BrandRepositoryInterface $brandRepository
     */
    public function __construct(CacheRepositoryInterface $cacheRepository, BrandRepositoryInterface $brandRepository)
    {
        $this->cacheRepository = $cacheRepository;
        $this->brandRepository = $brandRepository;
    }

    /**
     * @param int $id
     * @return Brand|null
     */
    public function findById(int $id): ?Brand
    {
        $item = $this->cacheRepository->rememberItem(
            "brands.{$id}",
            [$this->brandRepository, 'findById'],
            self::EXPIRES_AFTER_IN_SECONDS,
            $id
        );

        return $item->get();
    }

    /**
     * @return Brand[]
     */
    public function findAll(): array
    {
        $item = $this->cacheRepository->rememberItem(
            "brands.all",
            [$this->brandRepository, 'findAll'],
            self::EXPIRES_AFTER_IN_SECONDS
        );

        return $item->get();
    }
}

许可证

Caching Bundle 是开源软件,受 MIT 许可证 许可。