mesavolt / simple-cache-bundle
mesavolt/simple-cache的Symfony集成
v2.3.0
2023-07-28 13:40 UTC
Requires
- php: >=7.4
- mesavolt/simple-cache: ^2.2
Requires (Dev)
- php-coveralls/php-coveralls: ^2.1
- phpunit/phpunit: ^9.6
- roave/security-advisories: dev-latest
- symfony/config: ^5.4
- symfony/dependency-injection: ^5.4
- symfony/framework-bundle: ^5.4
- symfony/http-kernel: ^5.4
README
将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.default
或mesavolt.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 ]); } }