euskadi31/cache-service-provider

Silex 2.0 的缓存服务提供商,使用 doctrine/cache 包

v1.0 2015-06-17 14:32 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:04:16 UTC


README

Build Status SensioLabsInsight

此服务提供商为 Silex 2.0 使用 Doctrine Common 的 Cache 类,为 Silex 应用程序和其他服务提供商提供缓存服务。

安装

euskadi31/cache-service-provider 添加到您的 composer.json

% php composer.phar require euskadi31/cache-service-provider:~1.0

使用方法

配置

如果您只需要一个全局应用缓存,那么只需要定义一个默认缓存,通过在 cache.options 中设置 default 键即可。

缓存定义是一个选项数组,其中 driver 是唯一必需的选项。数组中的所有其他选项都被视为驱动类构造函数的参数。

名为 default 的缓存是通过应用的 cache 服务提供的缓存。

<?php

$app = new Silex\Application;

$app->register(new \Euskadi31\Silex\Provider\CacheServiceProvider, [
    'cache.options' => [
        'default' => [
            'driver' => 'apc'
        ]
    ]
]);

驱动器名称可以是

  • 一个完全限定的类名
  • 一个简单的标识符,如 "apc",它随后被转换为 \Doctrine\Common\Cache\ApcCache
  • 一个闭包,它返回一个实现 \Doctrine\Common\Cache\Cache 的对象。

此缓存然后可以通过 cache 服务访问,并提供一个 Doctrine\Common\Cache\Cache 的实例。

if ($app['cache']->contains('foo')) {
    echo $app['cache']->fetch('foo'), "<br />";
} else {
    $app['cache']->save('foo', 'bar');
}

要配置多个缓存,请将它们定义为 cache.options 中的附加键。

$app->register(new \Euskadi31\Silex\Provider\CacheServiceProvider, [
    'cache.options' => [
        'default' => [
            'driver' => 'apc'
        ],
        'file' => [
            'driver' => 'filesystem',
            'directory' => '/tmp/myapp'
        ],
        'global' => [
            'driver' => function() {
                $redis = new \Doctrine\Common\Cache\RedisCache;

                $redis->setRedis($app['redis']);

                return $redis;
            }
        ]
    ]
]);

所有缓存(包括默认缓存)都可以通过 caches 服务访问。

$app['caches']['file']->save('foo', 'bar');

许可

CacheServiceProvider 在 MIT 许可证 下授权。