Skip to content

Instantly share code, notes, and snippets.

@finalwebsites
Last active January 28, 2020 14:14
Show Gist options
  • Save finalwebsites/bcbd5cd1203869cb8c4eb3e624dbba77 to your computer and use it in GitHub Desktop.
Save finalwebsites/bcbd5cd1203869cb8c4eb3e624dbba77 to your computer and use it in GitHub Desktop.
Example scripts for PHP caching blog post
<?php
require_once __DIR__.'/../vendor/autoload.php';
try {
$cache = new PageCache\PageCache();
$cache->config()
->setCachePath('/your/cache_path/')
->setEnableLog(true)
->setCacheExpirationInSeconds(86400);
$cache->init();
} catch (\Exception $e) {
// Log PageCache error or simply do nothing.
// In case of a PageCache error, the page will load normally, without cache.
}
//The rest of your PHP code, everything below will be cached
<?php
$memcaches_obj = new Memcached();
$memcaches_obj->addServer('127.0.0.1', 11211);
if (!$value = $memcaches_obj->get('my_object_key')) {
$value = 'Some Value';
// store new values for 1 hour
$memcaches_obj->set('my_object_key', $value, 3600);
}
$memcaches_obj->quit();
<?php
try {
$redis = new Redis();
$redis->connect('localhost', 6379);
$redis->setEx('my_object_key', 3600, 'Some Value');
//get value
$value = $redis->get('my_object_key');
} catch (Exception $ex) {
echo $ex->getMessage();
}
<?php
use Phpfastcache\CacheManager;
use Phpfastcache\Drivers\Memcached\Config;
require __DIR__ . '/../../vendor/autoload.php';
$InstanceCache = CacheManager::getInstance('memcached', new Config([
'host' =>'127.0.0.1',
'port' => 11211
]));
$CachedString = $InstanceCache->getItem('my_object_key');
if (is_null($CachedString->get())) {
$CachedString->set('Some Value')->expiresAfter(60); // minutes
$InstanceCache->save($CachedString);
echo $CachedString->get();
} else {
echo $CachedString->get();
}
@finalwebsites
Copy link
Author

If you like to read my article where this examples are used?
Visit https://www.web-development-blog.com/why-should-you-cache-your-php-website/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment