Example scripts for PHP caching blog post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/