PHP code example of websolutionfalcon / laravel-simple-cold-storage

1. Go to this page and download the library: Download websolutionfalcon/laravel-simple-cold-storage 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/ */

    

websolutionfalcon / laravel-simple-cold-storage example snippets


use Websolutionfalcon\LaravelSimpleColdStorage\DTOs\StorageKey;
use Websolutionfalcon\LaravelSimpleColdStorage\Facades\LaravelSimpleColdStorage;

// Create a storage key
$key = new StorageKey('orders', '12345', 'archived');

// Store data
LaravelSimpleColdStorage::store(['order_id' => 12345, 'total' => 99.99], $key);

// Retrieve data
$data = LaravelSimpleColdStorage::retrieve($key);

// Check existence
if (LaravelSimpleColdStorage::exists($key)) {
    // Data exists
}

// Delete data
LaravelSimpleColdStorage::delete($key);

return [
    // Storage implementation class
    'storage' => \Websolutionfalcon\LaravelSimpleColdStorage\ColdStorage::class,

    // Settings passed to the storage implementation
    'settings' => [
        'disk' => env('COLD_STORAGE_DISK', 'local'),
        'prefix' => env('COLD_STORAGE_PREFIX', 'cold-storage'),
    ],

    // Encoder implementation class
    'encoder' => \Websolutionfalcon\LaravelSimpleColdStorage\Encoders\JsonEncoder::class,
];

// app/ColdStorage/Encoders/MsgPackEncoder.php

namespace App\ColdStorage\Encoders;

use Websolutionfalcon\LaravelSimpleColdStorage\Contracts\EncoderInterface;
use Websolutionfalcon\LaravelSimpleColdStorage\Exceptions\EncodingException;

class MsgPackEncoder implements EncoderInterface
{
    public function encode(mixed $data): string
    {
        try {
            return msgpack_pack($data);
        } catch (\Exception $e) {
            throw new EncodingException('Failed to encode: ' . $e->getMessage(), 0, $e);
        }
    }

    public function decode(string $data): mixed
    {
        try {
            return msgpack_unpack($data);
        } catch (\Exception $e) {
            throw new EncodingException('Failed to decode: ' . $e->getMessage(), 0, $e);
        }
    }

    public function getContentType(): string
    {
        return 'application/msgpack';
    }

    public function getFileExtension(): string
    {
        return 'msgpack';  // Files will have .msgpack extension
    }
}

// config/laravel-simple-cold-storage.php

return [
    'encoder' => \App\ColdStorage\Encoders\MsgPackEncoder::class,
    // ... rest of config
];

// app/ColdStorage/MySqlColdStorage.php

namespace App\ColdStorage;

use Illuminate\Support\Facades\DB;
use Websolutionfalcon\LaravelSimpleColdStorage\Contracts\ColdStorageInterface;
use Websolutionfalcon\LaravelSimpleColdStorage\Contracts\EncoderInterface;
use Websolutionfalcon\LaravelSimpleColdStorage\DTOs\StorageKey;
use Websolutionfalcon\LaravelSimpleColdStorage\Exceptions\StorageNotFoundException;

class MySqlColdStorage implements ColdStorageInterface
{
    public function __construct(
        protected EncoderInterface $encoder,
        protected string $table = 'cold_storage',
        protected ?string $connection = null
    ) {}

    public static function fromSettings(EncoderInterface $encoder, array $settings): static
    {
        return new static(
            encoder: $encoder,
            table: $settings['table'] ?? 'cold_storage',
            connection: $settings['connection'] ?? null
        );
    }

    public function store(mixed $data, StorageKey $key): void
    {
        $encoded = $this->encoder->encode($data);

        DB::connection($this->connection)->table($this->table)->updateOrInsert(
            [
                'type' => $key->type,
                'identifier' => $key->identifier,
                'variant' => $key->variant,
            ],
            [
                'data' => $encoded,
                'updated_at' => now(),
                'created_at' => now(),
            ]
        );
    }

    public function retrieve(StorageKey $key): mixed
    {
        $record = DB::connection($this->connection)
            ->table($this->table)
            ->where('type', $key->type)
            ->where('identifier', $key->identifier)
            ->where('variant', $key->variant)
            ->first();

        if (!$record) {
            throw new StorageNotFoundException("Not found: {$key}");
        }

        return $this->encoder->decode($record->data);
    }

    public function delete(StorageKey $key): bool
    {
        return DB::connection($this->connection)
            ->table($this->table)
            ->where('type', $key->type)
            ->where('identifier', $key->identifier)
            ->where('variant', $key->variant)
            ->delete() > 0;
    }

    public function exists(StorageKey $key): bool
    {
        return DB::connection($this->connection)
            ->table($this->table)
            ->where('type', $key->type)
            ->where('identifier', $key->identifier)
            ->where('variant', $key->variant)
            ->exists();
    }
}

// config/laravel-simple-cold-storage.php

return [
    'storage' => \App\ColdStorage\MySqlColdStorage::class,

    'settings' => [
        'table' => 'cold_storage',
        'connection' => null,  // Or 'mysql', 'pgsql', etc.
    ],

    'encoder' => \Websolutionfalcon\LaravelSimpleColdStorage\Encoders\JsonEncoder::class,
];

$oldOrders = Order::where('created_at', '<', now()->subYears(2))->get();

foreach ($oldOrders as $order) {
    $key = new StorageKey('orders', (string) $order->id, 'archived');

    LaravelSimpleColdStorage::store([
        'order_data' => $order->toArray(),
        'items' => $order->items->toArray(),
    ], $key);

    $order->update(['archived_key' => $key->toString()]);
    $order->delete();
}

$version = now()->format('Y-m-d-His');
$key = new StorageKey('backups', 'database', $version);

LaravelSimpleColdStorage::store([
    'tables' => $databaseDump,
    'created_at' => now(),
], $key);

$key = new StorageKey('sessions', session()->getId(), 'cart');

LaravelSimpleColdStorage::store([
    'items' => $cart->items,
    'total' => $cart->total,
], $key);

// With variant
$key = new StorageKey('users', '123', 'profile');

// Without variant
$key = new StorageKey('orders', '456');

// From string
$key = StorageKey::fromString('users:123:profile');

// To string
$str = $key->toString(); // "users:123:profile"
$str = (string) $key;     // "users:123:profile"

use Websolutionfalcon\LaravelSimpleColdStorage\Contracts\ColdStorageInterface;
use Websolutionfalcon\LaravelSimpleColdStorage\DTOs\StorageKey;

class OrderService
{
    public function __construct(
        protected ColdStorageInterface $coldStorage
    ) {}

    public function archiveOrder(Order $order): void
    {
        $key = new StorageKey('orders', (string) $order->id, 'archived');
        $this->coldStorage->store($order->toArray(), $key);
    }
}

// app/ColdStorage/Storages/MySqlColdStorage.php

namespace App\ColdStorage\Storages;

use Illuminate\Support\Facades\DB;
use Websolutionfalcon\LaravelSimpleColdStorage\Contracts\ColdStorageInterface;
use Websolutionfalcon\LaravelSimpleColdStorage\Contracts\EncoderInterface;
use Websolutionfalcon\LaravelSimpleColdStorage\DTOs\StorageKey;
use Websolutionfalcon\LaravelSimpleColdStorage\Exceptions\StorageNotFoundException;

class MySqlColdStorage implements ColdStorageInterface
{
    public function __construct(
        protected EncoderInterface $encoder,
        protected string $basePath,  // Used as table name
        protected ?string $connection = null
    ) {}

    public function store(mixed $data, StorageKey $key): void
    {
        $encoded = $this->encoder->encode($data);

        DB::connection($this->connection)->table($this->basePath)->updateOrInsert(
            [
                'type' => $key->type,
                'identifier' => $key->identifier,
                'variant' => $key->variant,
            ],
            [
                'data' => $encoded,
                'updated_at' => now(),
                'created_at' => now(),
            ]
        );
    }

    public function retrieve(StorageKey $key): mixed
    {
        $record = DB::connection($this->connection)
            ->table($this->basePath)
            ->where('type', $key->type)
            ->where('identifier', $key->identifier)
            ->where('variant', $key->variant)
            ->first();

        if (!$record) {
            throw new StorageNotFoundException("Not found: {$key}");
        }

        return $this->encoder->decode($record->data);
    }

    public function delete(StorageKey $key): bool
    {
        return DB::connection($this->connection)
            ->table($this->basePath)
            ->where('type', $key->type)
            ->where('identifier', $key->identifier)
            ->where('variant', $key->variant)
            ->delete() > 0;
    }

    public function exists(StorageKey $key): bool
    {
        return DB::connection($this->connection)
            ->table($this->basePath)
            ->where('type', $key->type)
            ->where('identifier', $key->identifier)
            ->where('variant', $key->variant)
            ->exists();
    }
}

// config/laravel-simple-cold-storage.php
return [
    'base_path' => 'cold_storage',  // table name
    'storage' => \App\ColdStorage\Storages\MySqlColdStorage::class,
];

use Websolutionfalcon\LaravelSimpleColdStorage\Exceptions\StorageNotFoundException;
use Websolutionfalcon\LaravelSimpleColdStorage\Exceptions\EncodingException;
use Websolutionfalcon\LaravelSimpleColdStorage\Exceptions\InvalidStorageKeyException;

try {
    $data = LaravelSimpleColdStorage::retrieve($key);
} catch (StorageNotFoundException $e) {
    // Data not found
} catch (EncodingException $e) {
    // Encoding/decoding failed
} catch (InvalidStorageKeyException $e) {
    // Invalid key format
}
bash
php artisan vendor:publish --provider="Websolutionfalcon\LaravelSimpleColdStorage\LaravelSimpleColdStorageServiceProvider" --tag="config"