Giter VIP home page Giter VIP logo

simple-cache's Introduction

Build Status FOSSA Status Coverage Status Scrutinizer Code Quality Codacy Badge Latest Stable Version Total Downloads License Donate to this project using Paypal Donate to this project using Patreon

โšก Simple Cache Class

This is a simple Cache Abstraction Layer for PHP >= 7.0 that provides a simple interaction with your cache-server. You can define the Adapter / Serializer in the "constructor" or the class will auto-detect you server-cache in this order:

  1. Memcached / Memcache
  2. Redis
  3. Xcache
  4. APC / APCu
  5. OpCache (via PHP-files)
  6. Static-PHP-Cache

Get "Simple Cache"

You can download it from here, or require it using composer.

{
  "require": {
    "voku/simple-cache": "4.*"
  }
}

Install via "composer require"

composer require voku/simple-cache

Quick Start

use voku\cache\Cache;

require_once 'composer/autoload.php';

$cache = new Cache();
$ttl = 3600; // 60s * 60 = 1h
$cache->setItem('foo', 'bar', $ttl);
$bar = $cache->getItem('foo');

Usage

use voku\cache\Cache;

$cache = new Cache();
  
if ($cache->getCacheIsReady() === true && $cache->existsItem('foo')) {
  return $cache->getItem('foo');
} else {
  $bar = someSpecialFunctionsWithAReturnValue();
  $cache->setItem('foo', $bar);
  return $bar;
}

If you have an heavy task e.g. a really-big-loop, then you can also use static-cache. But keep in mind, that this will be stored into PHP (it needs more memory).

use voku\cache\Cache;

$cache = new Cache();
  
if ($cache->getCacheIsReady() === true && $cache->existsItem('foo')) {
  for ($i = 0; $i <= 100000; $i++) {
    echo $this->cache->getItem('foo', 3); // use also static-php-cache, when we hit the cache 3-times
  }
  return $cache->getItem('foo');
} else {
  $bar = someSpecialFunctionsWithAReturnValue();
  $cache->setItem('foo', $bar);
  return $bar;
}

PS: By default, the static cache is also used by >= 10 cache hits. But you can configure this behavior via $cache->setStaticCacheHitCounter(INT).

No-Cache for the admin or a specific ip-address

If you use the parameter "$checkForUser" (=== true) in the constructor, then the cache isn't used for the admin-session.

-> You can also overwrite the check for the user, if you add a global function named "checkForDev()".

Overwrite the auto-connection option

You can overwrite the cache auto-detect via "CacheAdapterAutoManager" and the "$cacheAdapterManagerForAutoConnect" option in the "Cache"-constructor. Additional you can also activate the "$cacheAdapterManagerForAutoConnectOverwrite" option in the "Cache"-constructor, so that you can implement your own cache auto-detect logic.

$cacheManager = new \voku\cache\CacheAdapterAutoManager();

// 1. check for "APCu" support first
$cacheManager->addAdapter(
    \voku\cache\AdapterApcu::class
);

// 2. check for "APC" support
$cacheManager->addAdapter(
    \voku\cache\AdapterApcu::class
);

// 3. try "OpCache"-Cache
$cacheManager->addAdapter(
    \voku\cache\AdapterOpCache::class,
    static function () {
        $cacheDir = \realpath(\sys_get_temp_dir()) . '/simple_php_cache_opcache';

        return $cacheDir;
    }
);

// 4. try "File"-Cache
$cacheManager->addAdapter(
    \voku\cache\AdapterFileSimple::class,
    static function () {
        $cacheDir = \realpath(\sys_get_temp_dir()) . '/simple_php_cache_file';

        return $cacheDir;
    }
);


// 5. use Memory Cache as final fallback
$cacheManager->addAdapter(
    \voku\cache\AdapterArray::class
);

$cache = new \voku\cache\CachePsr16(
    null, // use auto-detection
    null, // use auto-detection
    false, // do not check for usage
    true, // enable the cache
    false, // do not check for admin session
    false, // do not check for dev
    false, // do not check for admin session
    false, // do not check for server vs. client ip
    '', // do not use "_GET"-parameter for disabling
    $cacheManager, // new auto-detection logic
    true // overwrite the auto-detection logic
);

Support

For support and donations please visit Github | Issues | PayPal | Patreon.

For status updates and release announcements please visit Releases | Twitter | Patreon.

For professional support please contact me.

Thanks

  • Thanks to GitHub (Microsoft) for hosting the code and a good infrastructure including Issues-Managment, etc.
  • Thanks to IntelliJ as they make the best IDEs for PHP and they gave me an open source license for PhpStorm!
  • Thanks to Travis CI for being the most awesome, easiest continous integration tool out there!
  • Thanks to StyleCI for the simple but powerfull code style check.
  • Thanks to PHPStan && Psalm for relly great Static analysis tools and for discover bugs in the code!

License

FOSSA Status

simple-cache's People

Contributors

bilge avatar dependabot-support avatar fossabot avatar gitter-badger avatar renovate[bot] avatar scrutinizer-auto-fixer avatar voku avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simple-cache's Issues

Plesk disables opcache_get_cache() in PHP

Hi Lars

Plesk changed its defaults to use
Plesk 17.8.11 - PHP value "disable_functions" changed to default value "opcache_get_status"
And Hosters tend do follow this approach.
โ€‹
/src/voku/cache/AdapterOpCache.php in Line 36 uses !empty(@\opcache_get_cache()) to check that op cache is enabled.

PHP 7.4 is @silenced, but PHP 8 errors in Userland. This disabled method could be replaced by

!empty(@\opcache_get_configuration())

I assume we better have something like

$opcache_get_configuration['directives']['opcache.enable'] === true

to ensure opcache is really enabled.

What do you think?

[Insight] Text files should end with a newline character - in LICENSE, line 19

in LICENSE, line 19

This file ends with no newline character. It won't render properly on a terminal, and it's considered a bad practice. Add a simple line feed as the last character to fix it.

IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Posted from SensioLabsInsight

opcache function call will cause warnings in hosting environments

For security reasons it's common to restrict the opcache API in shared webhosting environments.

This is usually no problem, because applications have little reason to call into the opcache api directly. But in your library (which recently got added as a dependency to the serendipity blog software) this is the case, and it will cause warnings like:

Warning: Zend OPcache API is restricted by "restrict_api" configuration directive in [path]/bundled-libs/voku/simple-cache/src/voku/cache/AdapterOpCache.php:32

See here for a similar issue in wp super cache:
https://github.com/Automattic/wp-super-cache/issues/536

One workaround would be to prefix the \opcache_get_status() with @ to avoid the warning, i.e. change the code to:

            self::$hasCompileFileFunction = \function_exists('opcache_compile_file') && !empty(@Bilge @\opcache_get_status());

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php >=7.0.0
  • psr/simple-cache ~1.0 || ~2.0
  • phpunit/phpunit ~6.0 || ~7.0 || ~9.0

  • Check this box to trigger a request for Renovate to run again on this repository

Possible to set cache dir?

Are feature requests okay here?

If I see that correctly the OpCache Constructor supports setting a cache dir, but the class above (Cache) seems to have no way to actually to set that variable when calling that constructor. Is there a way to configure it?

On some shared hosters you do not actually want to write to the configured PHP tmp directory, but rather to a project specific tmp directory.

Remove items with regex?

For granular cache invalidation it's useful to have a middle road option between removeAll() and removeItem(key), and that's removeThose(regexp). So that I can remove all the items with a prefix, like 'imagecache_%'.

It would help avoid having to create multiple caches. But I understand that given the various backends the feature might be cumbersome to implement.

2.0.1 composer breaks simple-mysqli

This is fixed in master but it isn't pushed as a release so it has broken simple-mysqli suddenly.

"autoload": {
    "psr-0": {
        "voku": "src"
    }
}

Needs to be:

"autoload": {
    "psr-0": {
        "voku\\cache\\": "src"
    }
}

[Insight] Commented code should not be commited - in src/voku/cache/AdapterMemcached.php, line 69

in src/voku/cache/AdapterMemcached.php, line 69

Commented out code reduces readability and lowers the code confidence for other developers. If it's common usage for debug, it should not be committed. Using a version control system, such code can be safely removed.

   * @return mixed|void
   */
  public function set($key, $value)
  {
    // Make sure we are under the proper limit
    /*
    if (strlen($this->memcached->getOption(\Memcached::OPT_PREFIX_KEY) . $key) > 250) {
      throw new \Exception('The passed cache key is over 250 bytes');
    }
    */

Posted from SensioLabsInsight

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.