Skip to content

Instantly share code, notes, and snippets.

@jonhassall
Created May 25, 2024 02:43
Show Gist options
  • Save jonhassall/1328a2eebda9fd4b6c9727680bb17164 to your computer and use it in GitHub Desktop.
Save jonhassall/1328a2eebda9fd4b6c9727680bb17164 to your computer and use it in GitHub Desktop.
====
config\cache.php:
====
'file-compressed' => [
'driver' => 'file-compressed',
'path' => storage_path('framework/cache/data'),
'file_chmod' => 0774,
],
====
app\Cache\CompressedFileStore:
====
<?php
namespace App\Cache;
use Illuminate\Cache\FileStore;
use App\Traits\CompressedCache;
//Extend FileStore to add compression
class CompressedFileStore extends FileStore
{
use CompressedCache;
}
====
app\Traits\CompressedCache.php
====
<?php
namespace App\Traits;
use Illuminate\Support\Facades\Cache;
trait CompressedCache
{
protected $compressionLevel = 1; // Default compression level (1-9)
public function get($key)
{
$data = parent::get($key);
if (!$data) {
return null;
}
return unserialize(gzuncompress($data));
}
public function put($key, $value, $minutes = null)
{
$compressedData = gzcompress(serialize($value), $this->compressionLevel);
return parent::put($key, $compressedData, $minutes);
}
// Optional to change compression level dynamically
public function setCompressionLevel($level)
{
$this->compressionLevel = $level;
}
}
====
app\Providers\AppServiceProvider.php
====
use App\Cache\CompressedFileStore;
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//Compressed file cache
$this->app->booting(function () {
//Compressed File Cache
Cache::extend('file-compressed', function (Application $app) {
return Cache::repository(new CompressedFileStore(
$app['files'],
$app['config']['cache.stores.file-compressed.path'],
$app['config']['cache.stores.file-compressed.file_chmod'],
1
));
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment