zfegg/psr11-symfony-cache

PSR-11 的 Symfony 缓存组件工厂

0.4.0 2024-08-13 15:34 UTC

This package is auto-updated.

Last update: 2024-09-13 15:49:44 UTC


README

GitHub Actions: Run tests Coverage Status Latest Stable Version Total Downloads License PHP Version Require

PSR-11 的 Symfony 缓存组件 工厂。

目录

安装

composer require zfegg/psr11-symfony-cache

使用方法

<?php
/** @var \Symfony\Component\Cache\Adapter\AdapterInterface $cache */
$cache = $container->get('other');

// The callable will only be executed on a cache miss.
$value = $cache->get('my_cache_key', function (\Symfony\Contracts\Cache\ItemInterface $item) {
    $item->expiresAfter(3600);

    // ... do some HTTP request or heavy computations
    $computedValue = 'foobar';

    return $computedValue;
});

echo $value; // 'foobar'

更多信息请参考 文档

容器

任何 PSR-11 容器都可以使用。为了做到这一点,您需要添加配置并注册一个指向 Zfegg\Psr11SymfonyCache\CacheFactory 的新服务。

以下是一些特定的容器示例,以帮助您入门。

Pimple 示例

// Create Container
$container = new \Xtreamwayz\Pimple\Container([
    // Cache using the default keys.
    'cache' => new \Zfegg\Psr11SymfonyCache\CacheFactory(),
    
    // Second cache using a different cache configuration
    'other' => function($c) {
        return \Zfegg\Psr11SymfonyCache\CacheFactory::other($c);
    },
    
    // Config
    'config' => [
        'cache' => [
            // At the bare minimum you must include a default adaptor.
            'default' => [  
                'type' => '',
                'options' => [],
            ],
            
            // Some other Adaptor.  Keys are the names for each adaptor
            'someOtherAdaptor' => [
                'type' => 'local',
                'options' => [
                    'root' => '/tmp/pimple'
                ],
            ],
        ],
    ]
]);

/** @var \Symfony\Component\Cache\Adapter\AdapterInterface $cache */
$cache = $container->get('other');
// The callable will only be executed on a cache miss.
$value = $cache->get('my_cache_key', function (\Symfony\Contracts\Cache\ItemInterface $item) {
    $item->expiresAfter(3600);

    // ... do some HTTP request or heavy computations
    $computedValue = 'foobar';

    return $computedValue;
});

echo $value; // 'foobar'

// ... and to remove the cache key
$cache->delete('my_cache_key');

Laminas 服务管理器

// Create the container and define the services you'd like to use
$container = new \Laminas\ServiceManager\ServiceManager([
    'factories' => [
        // Cache using the default keys.
        'fileSystem' => \Zfegg\Psr11SymfonyCache\CacheFactory::class,
        
        // Second cache using a different cache configuration
        'other' => [\Zfegg\Psr11SymfonyCache\CacheFactory::class, 'other'],
    ],
]);

// Config
$container->setService('config', [
    'cache' => [
        // At the bare minimum you must include a default adaptor.
        'default' => [  
            'type' => '',
            'options' => [],
        ],
        
        // Some other Adaptor.  Keys are the names for each adaptor
        'someOtherAdaptor' => [
            'type' => 'local',
            'options' => [
                'root' => '/tmp/pimple'
            ],
        ],
    ],
]);

/** @var \Symfony\Component\Cache\Adapter\AdapterInterface $cache */
$cache = $container->get('other');
// The callable will only be executed on a cache miss.
$value = $cache->get('my_cache_key', function (\Symfony\Contracts\Cache\ItemInterface $item) {
    $item->expiresAfter(3600);

    // ... do some HTTP request or heavy computations
    $computedValue = 'foobar';

    return $computedValue;
});

echo $value; // 'foobar'

// ... and to remove the cache key
$cache->delete('my_cache_key');

// CacheServiceAbstractFactory

$container->addAbstractFactory(\Zfegg\Psr11SymfonyCache\CacheServiceAbstractFactory::class);

$cacheDefault = $container->get("cache.default");
$cacheSomeOtherAdaptor = $container->get("cache.someOtherAdaptor");

// Get a psr 16 simple cache
$psr16CacheDefault = $container->get("simple-cache.default");
$psr16CacheSomeOtherAdaptor = $container->get("simple-cache.someOtherAdaptor");

框架

任何使用 PSR-11 的框架都应该可以正常工作。以下是一些特定的框架示例,以帮助您入门。

Mezzio

您需要添加配置并注册您希望使用的服务。有几种方法可以实现这一点,但推荐的方法是创建一个新的配置文件 config/autoload/cache.global.php

配置

config/config.php

添加 CacheServiceAbstractFactoryServiceManager

<?php

$providers = [
//  ...
\Zfegg\Psr11SymfonyCache\ConfigProvider::class,
]

config/autoload/cache.global.php

<?php
return [
    'dependencies' => [
        'factories' => [
            // Cache using the default keys.
            'fileSystem' => \Zfegg\Psr11SymfonyCache\CacheFactory::class,
            
            // Second cache using a different filesystem configuration
            'someOtherAdaptor' => [\Zfegg\Psr11SymfonyCache\CacheFactory::class, 'someOtherAdaptor'],
        ],
        'aliases' => [
           \Psr\Cache\CacheItemPoolInterface::class => 'fileSystem',
        ],
    ],
    'cache' => [
        // At the bare minimum you must include a default adaptor.
        'default' => [  
            'type' => '',
            'options' => [],
        ],
        
        // Some other Adaptor.  Keys are the names for each adaptor
        'someOtherAdaptor' => [
            'type' => 'local',
            'options' => [
                'root' => '/tmp/pimple'
            ],
        ],
    ],
];

Laminas

您需要添加配置并注册您希望使用的服务。有几种方法可以实现这一点,但推荐的方法是创建一个新的配置文件 config/autoload/cache.global.php

配置

config/autoload/cache.global.php

<?php
return [
    'service_manager' => [
        'factories' => [
            // Cache using the default keys.
            'fileSystem' => \Zfegg\Psr11SymfonyCache\CacheFactory::class,
            
            // Second cache using a different configuration
            'someOtherAdaptor' => [\Zfegg\Psr11SymfonyCache\CacheFactory::class, 'someOtherAdaptor'],
        ],
        'aliases' => [
           \Psr\Cache\CacheItemPoolInterface::class => 'fileSystem',
        ],
    ],
    
    'cache' => [
        // At the bare minimum you must include a default adaptor.
        'default' => [  
            'type' => '',
            'options' => [],
        ],
        
        // Some other Adaptor.  Keys are the names for each adaptor
        'someOtherAdaptor' => [
            'type' => 'local',
            'options' => [
                'root' => '/tmp/pimple'
            ],
        ],
    ],
];

Slim

public/index.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Symfony\Component\Cache\Adapter\AdapterInterface;
use \Symfony\Contracts\Cache\ItemInterface;

require '../vendor/autoload.php';

// Add Configuration
$config = [
    'settings' => [
        'cache' => [
            // At the bare minimum you must include a default adaptor.
            'default' => [  
                'type' => '',
                'options' => [],
            ],
            
            // Some other Adaptor.  Keys are the names for each adaptor
            'someOtherAdaptor' => [
                'type' => 'local',
                'options' => [
                    'root' => '/tmp/pimple'
                ],
            ],
        ],
    ],
];

$app = new \Slim\App($config);

// Wire up the factory
$container = $app->getContainer();

// Cache using the default keys.
$container['fileSystem'] = new \Zfegg\Psr11SymfonyCache\CacheFactory();

// Second cache using a different cache configuration
$container['someOtherAdaptor'] = function ($c) {
    return \Zfegg\Psr11SymfonyCache\CacheFactory::someOtherAdaptor($c);
};


// Example usage
$app->get('/example', function (Request $request, Response $response) {
    
    /** @var AdapterInterface $cache */
    $cache = $this->get('other');
    // The callable will only be executed on a cache miss.
    $value = $cache->get('my_cache_key', function (ItemInterface $item) {
        $item->expiresAfter(3600);
    
        // ... do some HTTP request or heavy computations
        $computedValue = 'foobar';
    
        return $computedValue;
    });
    
    echo $value; // 'foobar'
    
    // ... and to remove the cache key
    $cache->delete('my_cache_key');
});

$app->run();

配置

最小配置

最小配置至少需要定义一个服务和 "default" 适配器。

最小示例(使用 Zend Expressive 作为示例)

<?php

return [
    'cache' => [
        'default' => [  
            'type' => '',
            'options' => [],
        ],
    ],
];

使用此设置,您将使用 "default" 文件系统与 "default" 适配器。在此示例中,我们将使用本地文件适配器作为默认适配器。

完整配置

注意:需要 "default" 适配器。

完整示例

<?php

return [
    'cache' => [
        // At the bare minimum you must include a default adaptor.
        'default' => [  
            'type' => '',
            'options' => [],
        ],
        
        // Some other Adaptor.  Keys are the names for each adaptor
        'someOtherAdaptor' => [
            'type' => 'local',
            'options' => [
                'root' => '/tmp/pimple'
            ],
        ],
    ],
];

适配器

支持适配器的示例配置

APCu

此适配器是一个高性能、共享内存缓存。它可以通过将缓存内容存储在共享内存中(一个比许多其他组件,如文件系统,快得多的组件)显著提高应用程序的性能。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'APCu',
            'options' => [
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'version' => null, // Optional : Version of the cache items.
            ],
        ],
    ],
];

文档: APCu 缓存适配器

数组

通常,此适配器适用于测试目的,因为其内容存储在内存中,且不以任何方式持久化到运行中的 PHP 进程外部。它还可以在预热缓存时有用,因为它的 getValues() 方法。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Array',
            'options' => [
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'storeSerialized' => true, // Optional : values saved in the cache are serialized before storing them Default: true
                'maxLifetime' => 0, // Optional : the maximum lifetime (in seconds) of the entire cache.  Default: 0
                'maxItems' => 0, // Optional : the maximum number of items that can be stored in the cache.  Default: 0
            ],
        ],
    ],
];

文档: APCu 缓存适配器

此适配器允许组合任何数量的其他可用缓存适配器。从包含它们的第一个适配器获取缓存项,并将缓存项保存到所有给定的适配器中。这提供了一个简单高效的方法来创建分层缓存。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Chain',
            'options' => [
                'adapters' => [], // Required : The ordered list of adapter service names to fetch cached items
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'maxLifetime' => 0, // Optional : The max lifetime of items propagated from lower adapters to upper ones
            ],
        ],
    ],
];

文档: 链缓存适配器

Couchbase

此适配器使用一个(或多个)Couchbase 服务器实例在内存中存储值。与 APCu 适配器不同,并且与 Memcached 适配器相似,它不受当前服务器共享内存的限制;您可以独立于 PHP 环境存储内容。还可以利用服务器集群提供冗余和/或故障转移的能力。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Couchbase',
            'options' => [
                // Connection config
                // You must provide a client service, dsn(s) or connection information
                'client' => 'service-name', // Couch Service name.  Will be pulled from the container.
                'dsn' => 'string or array', // Dsn for connections.  Can be one dsn or an array of dsn's

                // Manual connection
                'username' => 'username', // Required for manual connection
                'password' => 'password', // Required for manual connection
                'operationTimeout' => 2500000, // Optional.  Default: 2500000
                'configTimeout' => 5000000, // Optional.  Default: 5000000
                'configNodeTimeout' => 2000000, // Optional.  Default: 2000000
                'viewTimeout' => 75000000, // Optional.  Default: 75000000
                'httpTimeout' => 75000000, // Optional.  Default: 75000000
                'configDelay' => 10000, // Optional.  Default: 10000
                'htconfigIdleTimeout' => 4294967295, // Optional.  Default: 4294967295
                'durabilityInterval' => 100000, // Optional.  Default: 100000
                'durabilityTimeout' => 5000000, // Optional.  Default: 5000000
                
                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'maxLifetime' => 0, // Optional : The max lifetime of items propagated from lower adapters to upper ones
            ],
        ],
    ],
];

文档: Couchbase 缓存适配器

文件系统

此适配器为无法在其环境中安装APCu或Redis等工具的用户提供了改进的应用性能。它将缓存项的过期时间和内容以常规文件的形式存储在本地挂载文件系统上的目录集合中。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Filesystem',
            'options' => [
                'directory' => '', // Optional : The main cache directory.  Default: directory is created inside the system temporary directory
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: '0'
            ],
        ],
    ],
];

文档:文件系统缓存适配器

Memcached

此适配器使用一个(或多个)Memcached服务器实例在内存中存储值。与APCu适配器不同,与Redis适配器类似,它不受当前服务器共享内存的限制;您可以在不依赖PHP环境的情况下存储内容。还可以利用服务器集群提供冗余和/或故障转移的能力。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Memcached',
            'options' => [
                // Connection config
                // A client service, or dsn(s).  Default: localhost
                'client' => 'service-name', // Memcached service name.  Will be pulled from the container.
                'dsn' => 'string or array', // Dsn for connections.  Can be one dsn or an array of dsn's

                // Options
                'auto_eject_hosts' => false, // Optional.  Default: false
                'buffer_writes' => false, // Optional.  Default: false
                'compression' => true, // Optional.  Default: true
                'compression_type' => 'fastlz', // Optional.  Default: Varies based on flags used at compilation
                'connect_timeout' => 1000, // Optional.  Default: 1000
                'distribution' => 'consistent', // Optional.  Default: consistent
                'hash' => 'md5', // Optional.  Default: md5
                'libketama_compatible' => true, // Optional.  Default: true
                'no_block' => true, // Optional.  Default: true
                'number_of_replicas' => 0, // Optional.  Default: 0
                'prefix_key' => '', // Optional.  Default: empty string
                'poll_timeout' => 1000, // Optional.  Default: 1000
                'randomize_replica_read' => false, // Optional.  Default: false
                'recv_timeout' => 0, // Optional.  Default: 0
                'retry_timeout' => 0, // Optional.  Default: 0
                'send_timeout' => 0, // Optional.  Default: 0
                'serializer' => 'php', // Optional.  Default: php
                'server_failure_limit' => 0, // Optional.  Default: 0
                'socket_recv_size' => 0, // Optional.  Default: varies by platform and kernel
                'socket_send_size' => 0, // Optional.  Default: varies by platform and kernel
                'tcp_keepalive' => false, // Optional.  Default: false
                'tcp_nodelay' => false, // Optional.  Default: false
                'use_udp' => false, // Optional.  Default: false
                'verify_key' => false, // Optional.  Default: false
                
                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'maxLifetime' => 0, // Optional : The max lifetime of items propagated from lower adapters to upper ones
            ],
        ],
    ],
];

文档:Memcached缓存适配器

PDO和Doctrine DBAL

此适配器将缓存项存储在SQL数据库中。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'PDO',
            'options' => [
                'client' => 'service-name', // Required: A client service, or dsn(s). 
                
                'db_table' => 'cache_items', // Optional.  The name of the table.  Default: cache_items
                'db_id_col' => 'item_id', // Optional.  The column where to store the cache id.  Default: item_id
                'db_data_col' => 'item_data', // Optional.  The column where to store the cache data.  Default: item_data
                'db_lifetime_col' => 'item_lifetime', // Optional.  The column where to store the lifetime.  Default: item_lifetime
                'db_time_col' => 'item_time', // Optional.  The column where to store the timestamp.  Default: item_time
                'db_username' => '', // Optional.  The username when lazy-connect
                'db_password' => '', // Optional.  The password when lazy-connect
                'db_connection_options' => '', // Optional.  An array of driver-specific connection options
                
                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'maxLifetime' => 0, // Optional : The max lifetime of items propagated from lower adapters to upper ones
            ],
        ],
    ],
];

文档:PDO & Doctrine DBAL缓存适配器

PHP 数组

这是一个高性能的静态数据(例如应用配置)缓存适配器,它经过优化并预先加载到OPcache内存存储中。它适用于启动后主要是只读的数据。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'PhpArray',
            'options' => [
                'filePath' => __DIR__ . '/somefile.cache', // Required: Single file where values are cached
                'backupCache' => 'service-name', // Required: A backup cache service
            ],
        ],
    ],
];

文档:PHP数组缓存适配器

PHP 文件

类似于文件系统适配器,此缓存实现将缓存条目写入磁盘,但与文件系统缓存适配器不同,PHP文件缓存适配器以原生PHP代码的形式写入和读取这些缓存文件。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'PhpFiles',
            'options' => [
                'directory' => '/some/dir/path', // Required: The main cache directory (the application needs read-write permissions on it)
                
                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'maxLifetime' => 0, // Optional : The max lifetime of items propagated from lower adapters to upper ones
            ],
        ],
    ],
];

文档:PHP文件缓存适配器

代理

此适配器包装了PSR-6兼容的缓存项池接口。它通过消耗任何实现Psr\Cache\CacheItemPoolInterface的实现,用于将应用程序的缓存项池实现与Symfony缓存组件集成。

它还可以在将项目存储在装饰池之前自动前缀所有键,从而有效地从一个池中创建多个命名空间池。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'proxy',
            'options' => [
                'psr6Service' => 'service-name', // Required: A PSR 6 cache service

                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'maxLifetime' => 0, // Optional : The max lifetime of items propagated from lower adapters to upper ones
            ],
        ],
    ],
];

文档:代理缓存适配器

Redis

此适配器使用一个(或多个)Redis服务器实例在内存中存储值。

与APCu适配器不同,与Memcached适配器类似,它不受当前服务器共享内存的限制;您可以在不依赖PHP环境的情况下存储内容。还可以利用服务器集群提供冗余和/或故障转移的能力。

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Redis',
            'options' => [
                // Connection config
                // A client service, or dsn(s) is required.  Default: localhost
                'client' => 'service-name', // Redis service name.  Will be pulled from the container.
                'dsn' => 'redis://[pass@][ip|host|socket[:port]][/db-index]', // Dsn for connections.

                // Connection Options.  Not needed if using a service.
                'class' => '\Redis', // Optional.  Specifies the connection library to return, either \Redis or \Predis\Client. Default: \Redis
                'compression' => true, // Optional.  Enables or disables compression of items. Default: true
                'lazy' => false, // Optional.  Enables or disables lazy connections to the backend. Default: false
                'persistent' => 0, // Optional.  Enables or disables use of persistent connections. Default: 0
                'persistent_id' => 'some-id', // Optional.  Specifies the persistent id string to use for a persistent connection. Default: null
                'read_timeout' => 0, // Optional.  Specifies the read timeout. Default: 0
                'retry_interval' => 0, // Optional.  Specifies the delay (in milliseconds) between reconnection attempts. Default: 0
                'tcp_keepalive' => 0, // Optional.  Specifies the TCP-keepalive timeout (in seconds) of the connection. Default: 0
                'timeout' => 30, // Optional.  Specifies the timeout (in seconds) used to connect to a Redis server. Default: 30
                
                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'maxLifetime' => 0, // Optional : The max lifetime of items propagated from lower adapters to upper ones
            ],
        ],
    ],
];

文档:Redis缓存适配器

这些文档,包括代码示例,均受Creative Commons BY-SA 3.0许可协议的许可。