PHP code example of emileperron / magic-cache

1. Go to this page and download the library: Download emileperron/magic-cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

emileperron / magic-cache example snippets




use Emileperron\MagicCache\Cache;

// Saving data to cache
// Definition: set($key, $value, $expiresAfter = 0)
Cache::set('my_cache_key', 'my value');
Cache::set('my_cache_key_2', 'my second value', 3600);
Cache::set('my_cache_key_3', ['obj' => 'value']);

// Getting data from cache
// Definition: get($key, $fallback = null)
Cache::get('my_cache_key');
Cache::get('my_non_existing_key', 'fallback value');
// The $fallback parameter also allows for callables
Cache::get('my_non_existing_key', 'MyClass::myCallbackMethod');
Cache::get('my_non_existing_key', ['MyClass', 'myCallbackMethod']);
Cache::get('my_non_existing_key', function(){
	return 'fallback value';
});

// Manually removing data from cache
// Definition: remove($key)
Cache::remove('my_cache_key_3');

// Pruning the cache (deletes all expired cache entries)
// Definition: prune()
Cache::prune();

// This library defines two magic methods: magicGet() and magicSet()
// These methods automatically generate a cache key based on the calling function's class, name and parameters.
// Here's an example:
function getRecordFromDatabase($id)
{
	return Cache::magicGet([], function() use ($id) {
		$value = fetchValueFromDatabase($id); // replace this with your own data fetching/processing code
		return Cache::magicSet($value);
	});
}

// The definition of both methods goes as follows:
// magicGet($fallback = null, $suffixes = [])
// magicSet($value, $expiresAfter = 0, $suffixes = [])