mesavolt/simple-cache-bundle

mesavolt/simple-cache的Symfony集成

安装: 908

依赖者: 0

建议者: 0

安全: 0

星标: 1

关注者: 2

分支: 0

公开问题: 1

类型:symfony-bundle

v2.3.0 2023-07-28 13:40 UTC

This package is auto-updated.

Last update: 2024-08-28 15:56:31 UTC


README

Latest Stable Version License

mesavolt/simple-cache集成到您的Symfony应用程序中。

默认情况下,它将缓存写入到Symfony的缓存目录(%kernel.cache_dir%)的磁盘上,并使用空命名空间,但这两个选项都可以进行配置。

安装

使用Symfony Flex的应用程序

打开命令行控制台,进入您的项目目录并执行

composer require mesavolt/simple-cache-bundle

就这些。Flex会自动为您启用这个包。请参阅README中的配置部分,了解如何自定义包的行为。

不使用Symfony Flex的应用程序

步骤1:下载包

打开命令行控制台,进入您的项目目录并执行以下命令以下载此包的最新稳定版本

composer require mesavolt/simple-cache-bundle

此命令需要您全局安装Composer,请参阅Composer文档中的安装章节

步骤2:启用包

然后,通过将其添加到项目的app/AppKernel.php文件中注册的包列表中来启用包

<?php
// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Mesavolt\SimpleCacheBundle\SimpleCacheBundle(),
        );

        // ...
    }

    // ...
}

配置

以下选项可用于自定义包的缓存服务的行为

不使用Symfony Flex的应用程序

创建config/services/simple_cache.yaml并修改其内容

simple_cache:
    namespaces: 
      - default
      - specific
    cache_dir: /tmp/cache

不使用Symfony Flex的应用程序

将其添加到您的app/config/config.yml文件中并修改选项

simple_cache:
    namespaces:
      - default
      - specific
    cache_dir: /tmp/cache

使用方法

要获取Mesavolt\SimpleCache实例,您可以

  • 通过类型提示Mesavolt\SimpleCache来注入与第一个命名空间关联的缓存
  • 从容器中获取mesavolt.simple_cache.defaultmesavolt.simple_cache.specific服务
  • 注入Mesavolt\SimpleCacheBundle\SimpleCachePool服务并使用getCache($namespace)方法通过其命名空间获取缓存
<?php

namespace App;


use Mesavolt\SimpleCache;
use Mesavolt\SimpleCacheBundle\SimpleCachePool;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\HttpFoundation\Response;

class HomeController extends AbstractController
{
    public function demo1(SimpleCache $cache): Response
    {
        // $cache is the cache configured with the 'default' namespace
        $time = $cache->get('val', function () {
            return time();
        }, SimpleCache::TTL_30_MINUTES);
        
        return $this->render('home/demo.html.twig', [
            'time' => $time
        ]);
    }

    public function demo2(): Response
    {
        $time = $this->get('mesavolt.simple_cache.default')->get('val', function () {
            return time();
        }, SimpleCache::TTL_30_MINUTES);

        return $this->render('home/demo.html.twig', [
            'time' => $time
        ]);
    }

    public function demo3(SimpleCachePool $pool): Response
    {
        $time = $pool->getCache('specific')->get('val', function () {
            return time();
        }, SimpleCache::TTL_30_MINUTES);

        return $this->render('home/demo.html.twig', [
            'time' => $time
        ]);
    }
}