@extends('layouts.docs') @section('title', 'Cache System - OG Framework') @section('body')
{{-- Floating shapes for styling --}}
{{-- Left Sidebar: Navigation --}} @include('docs.partials.sidebar') {{-- Main Content --}}
{{-- Page Header --}}
Voltar para Documentação

System

Cache System

API unificada e expressiva para diversos backends de armazenamento em cache, otimizada para performance e flexibilidade.

{{-- Introduction --}}

Introdução

O sistema de cache do OfficeGest oferece uma interface consistente para drivers como Redis, Files e Database. A configuração reside em Modules/Common/Config/cache.php e pode ser ajustada via variáveis de ambiente .env.

{{-- Architecture (SVG) --}}

Arquitetura do Sistema

Application Cache::get() Cache Facade Proxy -> Manager Cache Drivers Redis (Memory) Database (SQL) File System
{{-- Basic Usage --}}

Recuperar e Guardar Itens

A Facade Cache é a porta de entrada principal.

{{-- Method: GET --}}

Cache::get($key, $default = null)

Recupera um valor. Se não existir, retorna null ou o valor default.

// Simples
$value = Cache::get('key');

// Com default
$value = Cache::get('key', 'default_value');

// Com Closure (lazy evaluation)
$value = Cache::get('settings', function () {
    return DB::table('settings')->get();
});
{{-- Method: PUT --}}

Cache::put($key, $value, $seconds)

Armazena um item por um tempo determinado.

// Guardar por 60 segundos
Cache::put('key', 'meu_valor', 60);

// Arrays são serializados automaticamente
Cache::put('user:profile', ['name' => 'Paulo', 'role' => 'admin'], 600);
{{-- Method: REMEMBER --}}

Cache::remember($key, $seconds, $callback)

Tenta obter do cache. Se não existir, executa a closure, guarda o resultado e retorna. Método mais comum e eficiente.

$users = Cache::remember('all_users', 600, function () {
    return DB::table('users')->get();
});
{{-- Other Methods --}}

Cache::has($key)

Verifica existência (retorna bool).

Cache::add($key, $val, $sec)

Adiciona apenas se NÃO existir. Retorna true se adicionou (Lock atómico).

{{-- Removing Items --}}

Remover Itens

// Remover um item
Cache::forget('key');
// Limpar TUDO (Cuidado!)
Cache::clearAll();
{{-- Configuration --}}

Configuração e Drivers

Configurável via .env. Em produção, prefira Redis.

Modules/Common/Config/cache.php
return [
    'default' => envVar('CACHE_DRIVER', 'redis'),

    'stores' => [
        'file' => [
            'driver' => 'file',
            'path' => rootPath("_cache/{$server}cache"),
        ],
        
        'redis' => [
            'driver' => 'redis',
            'connection' => 'cache',
            'prefix' => "{$serverCachePrefix}_cache",
        ],
    ],
];
{{-- Real Examples --}}

Exemplos Práticos

Casos de uso reais extraídos do código do OfficeGest.

{{-- Exemplo 1 --}}

1. Cache de Configurações Externas (WMS)

Evita chamadas de API repetitivas usando remember.

return Cache::remember('wms_configs', 5, function () {
    return $this->connection->makeHttpCall(url: "configs");
});
{{-- Exemplo 2 --}}

2. Estado de Processamento em Lote

Uso de put e get para gestão de estado mutável.

// Inicializar
Cache::put("batch:123:state", ['status' => 'pending'], 86400);

// Atualizar depois
$state = Cache::get("batch:123:state");
$state['status'] = 'processing';
Cache::put("batch:123:state", $state, 86400);
{{-- Exemplo 3 --}}

3. Listas para Dropdowns (Select2)

Cache longo para dados estáticos de base de dados.

$statusTypes = Cache::remember('wmso_select2_status_types', 3600, function () {
    return $this->database->from('status_types')->get()->result();
});
{{-- Troubleshooting --}}

Troubleshooting

Não serializa?

Evite salvar objetos com recursos (streams, conexões DB) dentro. O Cache usa serialize() e vai falhar.

Dados antigos?

Lembre-se de usar Cache::forget() quando atualizar o dado original na DB.

{{-- Navigation --}}
{{-- Right Sidebar: Table of Contents --}} @include('docs.partials.toc', ['sections' => [ 'introducao' => 'Introdução', 'arquitetura' => 'Arquitetura', 'uso-basico' => 'Recuperar e Guardar', 'remover' => 'Remover Itens', 'configuracao' => 'Configuração', 'exemplos' => 'Exemplos Práticos', 'troubleshooting' => 'Troubleshooting', ]])
@endsection