承接 nilportugues/cache 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

nilportugues/cache

Composer 安装命令:

composer require nilportugues/cache

包简介

Cache layer for PHP applications using the on Chain of responsability pattern

README 文档

README

Build Status Coverage Status Scrutinizer Code Quality SensioLabsInsight Latest Stable Version Total Downloads License Donate

Cache layer for PHP applications capable of being used standalone or with the Chain of Responsability pattern.

1. Installation

The recommended way to install this package is through Composer. Run the following command to install it:

php composer.phar require nilportugues/cache

2. Features

  • One cache class, many adapters.
  • All cache adapters can be used as standalone cache classes.
  • Opt-in to be used as a chain of caches.
  • Implementation normalizes all mechanisms and behaviours.
  • Configuration files for all adapters in vanilla PHP and Symfony2 format provided in configand migrations directories.
  • High quality, 100% tested code.

3. Drivers Available

The package provides several implementations for a key-value cache.

The most sensitive choice is to make use of the Cache based adapters such as Redis and Memcached, which are the most performant and specialized.

Yet sometimes these are not available and other options should be considered, but we got you covered.

Cache based:

  • Memcached: MemcachedAdapter (php5-memcached)
  • Redis: RedisAdapter (php5-redis), PredisAdapter (Predis)

Full-text based:

  • SphinxQL: SphinxAdapter
  • ElasticSearch: ElasticSearchAdapter

System based:

  • Memory: InMemoryAdapter
  • FileSystem: FileSystemAdapter

Database based:

  • MySQL: MySqlAdapter
  • PostgreSql: PostgreSqlAdapter
  • Sqlite: SqliteAdapter

4. Cache and CacheAdapter Interfaces

These are all the public methods available for the Cache and all of its available adapters:

  • get($key): Get a value identified by $key.
  • set($key, $value, $ttl = 0): Set a value identified by $key and with an optional $ttl.
  • defaultTtl($ttl): Allows to set a default ttl value if none is provided for set()
  • delete($key): Delete a value identified by $key.
  • isAvailable(): Checks the availability of the cache service.
  • isHit(): Check if value was found in the cache or not.
  • clear(): Clears all expired values from cache.
  • drop(): Clears all values from the cache.

4.1 - CacheAdapter

Allows all of the public methods defined in Cache Interface.

Each CacheAdapter will have a custom constructor method due to its needs, but last parameter is always a chainable value, being another CacheAdapter.

5. Example

The more cache levels the slower the cache system will be, so leverage the 
cache to your needs. 
Maybe you don't need a fallback mechanism at all! This is just an example.

1st level cache Redis (PredisAdapter) is our main cache, in a dedicated server.

2nd level cache Memcached (MemcachedAdapter) as fallback mechanism, available in the same machine as our PHP script.

Application cache InMemoryAdapter, used to avoid hiting the external caches on repeated operations and is shared by all cache layers. This comes enabled by default so you don't need to worry at all.

5.1. Configuration

Using a Service Container, such as an array returning the services or a more popular solution such as Symfony's Service Container, build the caches.

For this example, we'll be building two caches, user_cache and image_cache. Both use Predis as first level cache and a fallback to Memcached if Predis cannot establish a connection during runtime.

<?php
include_once realpath(dirname(__FILE__)).'/vendor/autoload.php';

use NilPortugues\Cache\Adapter\MemcachedAdapter;
use NilPortugues\Cache\Adapter\PredisAdapter;
use NilPortugues\Cache\Cache;

$parameters = include_once realpath(dirname(__FILE__)).'/cache_parameters.php';

$cache = new PredisAdapter(
    $parameters['redis'],
    //here we're chaining the $memcachedAdapter
    new MemcachedAdapter(
        $parameters['memcached']['persistent_id'],
        $parameters['memcached']['connections']
    );
);

return [
    'user_cache' => new Cache($cache, 'user', 60*5), //5 minutes cache
    'image_cache' => new Cache($cache, 'image', 60*60), //1 hour cache
];

5.2. Usage

Now, using a Service Container, we'll get the user_cache to fetch data, or add if it does not exist. This data will be stored in the caches.

For fetching, first it's checked if data is available in memory, if not, it's fetched from the data storage, added to the in memory cache and returned to the user.

$db = $this->serviceContainer->get('database');
$cache = $this->serviceContainer->get('cache');

$userId = 1;
$cacheKey = sprintf("user:id:%s", $userId);

$user = $cache->get($cacheKey);
if(null !== $user) {
  return $user;
}

$user = $db->findById($userId);
$cache->set($cacheKey, $user);

return $user;

And that's pretty much it. Notice how same key is used for the get and set methods.

5.3 Other configurations

5.3.1 ElasticSearch as cache

It is important that you configure your ElasticSearch by appending the following line to the elasticsearch.yml file:

indices.ttl.interval: 1s

Now restart the ElasticSearch daemon.

If you're wondering where the cache index definition is, the creation of index is handled by the adapter on instantiation if it does not already exist.

5.3.2 Sphinx as cache

Configuration provided in the /migrations/sphinx.conf file.

5.3.3 MySQL as cache

Configuration provided in the /migrations/mysql_schema.sql file.

5.3.4 Postgres as cache

Configuration provided in the /migrations/postgresql_schema.sql file.

5.3.5 Sqlite as cache

Configuration provided in the /migrations/sqlite_schema.sqlite file.

6. Quality

To run the PHPUnit tests at the command line, go to the tests directory and issue phpunit.

This library attempts to comply with PSR-1, PSR-2, and PSR-4. If you notice compliance oversights, please send a patch via pull request.

7. Author

Nil Portugués Calderó

8. License

The code base is licensed under the MIT license.

nilportugues/cache 适用场景与选型建议

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

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 119
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 7
  • 点击次数: 31
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-04-09