PHP code example of nette / caching

1. Go to this page and download the library: Download nette/caching 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/ */

    

nette / caching example snippets


use Nette\Caching\Cache;

$storage // instance of Nette\Caching\IStorage

$cache = new Cache($storage, 'Full Html Pages');

$value = $cache->load($key, function () use ($key) {
	$computedValue = ...; // heavy computations
	return $computedValue;
});

$cache->remove($key);

$result = $cache->call('gethostbyaddr', $ip);

function factorial($num)
{
	return ...;
}

$memoizedFactorial = $cache->wrap('factorial');

$result = $memoizedFactorial(5); // counts it
$result = $memoizedFactorial(5); // returns it from cache

$cache->save($key, $value, [
	Cache::Expire => '20 minutes',
]);

$value = $cache->load($key, function (&$dependencies) {
	$dependencies[Cache::Expire] = '20 minutes';
	return ...;
]);

$value = $cache->load($key, function () {
	return ...;
], [Cache::Expire => '20 minutes']);

// it also accepts the number of seconds or the UNIX timestamp
$dependencies[Cache::Expire] = '20 minutes';

$dependencies[Cache::Sliding] = true;

$dependencies[Cache::Files] = '/path/to/data.yaml';
// nebo
$dependencies[Cache::Files] = ['/path/to/data1.yaml', '/path/to/data2.yaml'];

$dependencies[Cache::Items] = ['frag1', 'frag2'];

function checkPhpVersion($ver): bool
{
	return $ver === PHP_VERSION_ID;
}

$dependencies[Cache::Callbacks] = [
	['checkPhpVersion', PHP_VERSION_ID] // expire when checkPhpVersion(...) === false
];

$dependencies[Cache::Expire] = '20 minutes';
$dependencies[Cache::Files] = '/path/to/data.yaml';

$dependencies[Cache::Tags] = ["article/$articleId", "comments/$articleId"];

$cache->clean([
	Cache::Tags => ["article/$articleId"],
]);

$cache->clean([
	Cache::Tags => ["comments/$articleId"],
]);

$dependencies[Cache::Priority] = 50;

$cache->clean([
	Cache::Priority => 100,
]);

$cache->clean([
	Cache::All => true,
]);

$values = $cache->bulkLoad($keys);

$values = $cache->bulkLoad($keys, function ($key, &$dependencies) {
	$computedValue = ...; // heavy computations
	return $computedValue;
});

if ($capture = $cache->start($key)) {

	echo ... // printing some data

	$capture->end(); // save the output to the cache
}

// the storage will be the directory '/path/to/temp' on the disk
$storage = new Nette\Caching\Storages\FileStorage('/path/to/temp');

$storage = new Nette\Caching\Storages\MemcachedStorage('10.0.0.158');

$storage = new Nette\Caching\Storages\MemoryStorage;

$storage = new Nette\Caching\Storages\SQLiteStorage('/path/to/cache.sdb');

$storage = new Nette\Caching\Storages\DevNullStorage;
html
{cache $id, expire => '20 minutes', tags => [tag1, tag2]}
	...
{/cache}
html
{cache $id, if => !$form->isSubmitted()}
	{$form}
{/cache}