locomotivemtl/charcoal-cache 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

locomotivemtl/charcoal-cache

Composer 安装命令:

composer require locomotivemtl/charcoal-cache

包简介

Charcoal service provider for the Stash Cache Library

README 文档

README

License Latest Stable Version Code Quality Coverage Status SensioLabs Insight Build Status

A Charcoal service provider for the Stash Cache Library.

Table of Contents

Installation

  1. The preferred (and only supported) method is with Composer:

    $ composer require locomotivemtl/charcoal-cache
  2. Add the service provider and configure the default caching service via the application configset:

    "service_providers": {
        "charcoal/cache/service-provider/cache": {}
    },
    
    "cache": {
        "prefix": "foobar",
        "types": [ "apc", "memcache", "redis" ]
    }

    or via the service container:

    $container->register(new \Charcoal\Cache\ServiceProvider\CacheServiceProvider());
    
    $container['cache/config'] = new \Charcoal\Cache\CacheConfig([
    	'prefix' => 'foobar',
    	'types'  => [ 'apc', 'memcache', 'redis' ],
    ]);

If you are using locomotivemtl/charcoal-app, the CacheServiceProvider is automatically registered by the AppServiceProvider.

Dependencies

Required

PSR

  • PSR-3: Common interface for logging libraries. Supported by Stash.
  • PSR-6: Common interface for caching libraries. Fulfilled by Stash.
  • PSR-7: Common interface for HTTP messages. Followed by CacheMiddleware.
  • PSR-11: Common interface for dependency containers. Fulfilled by Pimple.

Dependents

Service Provider

Parameters

  • cache/available-drivers: Collection of registered cache drivers that are supported by this system (via Stash\DriverList).

Services

  • cache/config: Configuration object for the caching service.
    See Pool Configuration for available options.
  • cache/drivers: Collection of cache driver instances (as a service container) which uses cache/available-drivers.
    These drivers are pre-configured:
  • cache/builder: Instance of CacheBuilder that is used to build a cache pool.
  • cache/driver: Reference to the Stash cache driver used by cache. Defaults to "memory".
  • cache: Main instance of the Stash cache pool which uses cache/driver and cache/config.prefix.

Configuration

Pool Configuration

Each pool comes with a set of default options which can be individually overridden.

Setting Type Default Description
active boolean TRUE Whether to enable or disable the cache service.
prefix string charcoal Name of the main Stash pool.
types string[] memory List of cache drivers to choose from for the main Stash pool. Defaults to "memory".
default_ttl integer 1 week Default time-to-live (in seconds) for a cached item. Currently, only used by the APC driver (cache/drivers.apc).

Driver Configuration

Each driver comes with a set of default options which can be individually overridden.

—N/A—

Usage

Just fetch the default cache pool service:

$pool = $this->container->get('cache');

Or a custom-defined cache pool:

// Create a Stash pool with the Memcached driver and a custom namespace.
$pool1 = $this->container->get('cache/builder')->build('memcache', 'altcache');

// Create a custom Stash pool with the FileSystem driver and custom features.
$pool2 = $this->container->get('cache/builder')->build('file', [
    'namespace'  => 'mycache',
    'logger'     => $this->container->get('logger.custom_logger'),
    'pool_class' => \MyApp\Cache\Pool::class,
    'item_class' => \MyApp\Cache\Item::class,
]);

// Create a Stash pool with the "memory" cache driver.
$pool3 = new \Stash\Pool($container['cache/drivers']['memory']);

Then you can use the cache service directly:

// Get a Stash object from the cache pool.
$item = $pool->getItem("/user/{$userId}/info");

// Get the data from it, if any happens to be there.
$userInfo = $item->get();

// Check to see if the cache missed, which could mean that it either
// didn't exist or was stale.
if ($item->isMiss()) {
    // Run the relatively expensive code.
    $userInfo = loadUserInfoFromDatabase($userId);

    // Set the new value in $item.
    $item->set($userInfo);

    // Store the expensive code so the next time it doesn't miss.
    $pool->save($item);
}

return $userInfo;

See the Stash documentation for more information on using the cache service.

Middleware

The CacheMiddleware is available for PSR-7 applications that support middleware. The middleware saves the HTTP response body and headers into a PSR-6 cache pool and returns that cached response if still valid.

If you are using locomotivemtl/charcoal-app, you can add the middleware via the application configset:

"middlewares": {
    "charcoal/cache/middleware/cache": {
        "active": true,
        "methods": [ "GET", "HEAD" ]
    }
}

Otherwise, with Slim, for example:

$app = new \Slim\App();

// Register middleware
$app->add(new \Charcoal\Cache\Middleware\CacheMiddleware([
    'cache'   => new \Stash\Pool(),
    'methods' => [ 'GET', 'HEAD' ],
]));

The middleware comes with a set of default options which can be individually overridden.

Setting Type Default Description
active boolean FALSE Whether to enable or disable the middleware (locomotivemtl/charcoal-app only).
cache CacheItemPoolInterface cache Required; The main Stash pool.
ttl string[] 1 week Time-to-live (in seconds) for a cached response.
methods string[] GET Accepted HTTP method(s) to cache the response.
status_codes integer[] 200 Accepted HTTP status code(s) to cache the response.
included_path string[] * Accepted URI paths for caching the response.
excluded_path string[] ^/admin\b Rejected URI paths for caching the response.
included_query string[] NULL Accepted query parameters for caching the response.
excluded_query string[] NULL Rejected query parameters for caching.
ignored_query string[] NULL Ignored query parameters for caching the response.

By Default

All HTTP responses are cached unless:

  1. the request method is not GET
  2. the request URI path starts with /admin…
  3. the request URI contains a query string
  4. the response is not OK (200)

Ignoring Query Strings

If query strings don't affect the server's response, you can permit caching of requests by ignoring all query parameters:

"ignored_query": "*"

or some of them:

"ignored_query": [ "sort", "theme" ]

Helpers

CachePoolAwareTrait

The CachePoolAwareTrait is offered as a convenience to avoid duplicate / boilerplate code. It simply sets and gets an instance of \Psr\Cache\CacheItemPoolInterface.

Assign a cache pool with setCachePool() and retrieve it with cachePool().

Both methods are protected; this trait has no public interface.

Development

To install the development environment:

$ composer install

To run the scripts (phplint, phpcs, and phpunit):

$ composer test

API Documentation

Development Dependencies

Coding Style

The charcoal-cache module follows the Charcoal coding-style:

Coding style validation / enforcement can be performed with composer phpcs. An auto-fixer is also available with composer phpcbf.

Credits

License

  • Charcoal is licensed under the MIT license. See LICENSE for details.
  • Stash is licensed under the BSD License. See the LICENSE file for details.

locomotivemtl/charcoal-cache 适用场景与选型建议

locomotivemtl/charcoal-cache 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10.81k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2018 年 04 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「cache」 「caching」 「stash」 「charcoal」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 locomotivemtl/charcoal-cache 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 locomotivemtl/charcoal-cache 我们能提供哪些服务?
定制开发 / 二次开发

基于 locomotivemtl/charcoal-cache 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 10.81k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 16
  • 依赖项目数: 4
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 11
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-04-13