OG Framework
OG Framework Documentação
Voltar para Documentação

Arquitetura

Facades

Facades fornecem uma interface estática elegante para serviços do container. Em vez de app('cache')->get('key'), use simplesmente Cache::get('key').

Como Funcionam?

Cache::get('key') __callStatic('get', ['key']) getFacadeAccessor() → 'cache' Container::get('cache') CacheManager 1. Chamada 2. Método mágico 3. Accessor 4. Container 5. Serviço Real
Aspecto Sem Facade Com Facade
Sintaxe Verbosa Concisa
Testabilidade Manual mocking spy(), mock() built-in
IDE Support Limitado PHPDoc completo

Quick Start

use Og\Modules\Common\Facades\Cache;
use Og\Modules\Common\Facades\Auth;
use Og\Modules\Common\Facades\Queue;
use Og\Modules\Common\Facades\Http;

// CACHE - armazenar e recuperar dados
Cache::put('user:1', $userData, 60);
$user = Cache::get('user:1');

// AUTH - verificar utilizador
if (Auth::check()) {
    $userId = Auth::id();
    $canEdit = Auth::can('posts:edit');
}

// QUEUE - enviar jobs para background
Queue::dispatch(new SendEmailJob($user));

// HTTP - fazer requests externos
$response = Http::get('https://api.example.com/users');

Import Múltiplo

use Og\Modules\Common\Facades\{
    Auth, Cache, Queue, Http,
    Route, View, File, Notification
};

11 Facades Disponíveis

Facade Accessor Uso
Auth 'auth' Verificar utilizador e permissões
Cache 'cache' Cache distribuído (Redis)
Queue QueueManagerInterface Jobs em background
Http 'http-client' Requests HTTP externos
Route RouterClass Definição de rotas
View 'view' Renderizar templates
File Filesystem::class Operações de ficheiros
Notification NotificationService Email, SMS, Push
Request 'request' Dados do request actual
Response 'response' Construir responses
GuardFacade 'guard' Tokens e SPA auth

Exemplos por Facade

Cache

// Operações básicas
Cache::put('key', $value, 60);   // Guardar por 60s
$value = Cache::get('key');       // Recuperar
Cache::forget('key');             // Remover

// Remember pattern (cache inteligente)
$data = Cache::remember('expensive', 300, function() {
    return $this->heavyQuery();
});

// Multi-tenant
Cache::replacePrefix('tenant:123:');

Queue

// Dispatch simples
Queue::dispatch(new SendEmailJob($user));

// Com delay
Queue::later(now()->addMinutes(5), new ReminderJob());

// Batch de jobs
Queue::batch([
    new ProcessJob($item1),
    new ProcessJob($item2),
]);

// Chain sequencial
Queue::chain([
    new ImportDataJob(),
    new ValidateDataJob(),
    new GenerateReportJob(),
]);

Http

// GET request
$response = Http::get('https://api.example.com/users');

// POST com dados
$response = Http::post('https://api.example.com/users', [
    'name' => 'João',
    'email' => 'joao@email.com',
]);

// Com headers
$response = Http::withHeaders([
    'Authorization' => 'Bearer ' . $token,
])->get('https://api.example.com/protected');

// Base URL
$response = Http::baseUrl('https://api.example.com')
    ->get('/users');

Route

// Rotas básicas
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);

// Controller group
Route::controller(InvoiceController::class)->group(function() {
    Route::get('/invoices', 'index');
    Route::post('/invoices', 'store');
});

Criar uma Facade

Modules/Common/Facades/Auth.php — Exemplo real do sistema:

namespace Og\Modules\Common\Facades;

use Og\Modules\Common\Utils\Facade;

/**
 * @method static user()
 * @method static id()
 * @method static check()
 * @method static can(string $permission)
 * @method static isImpersonating()
 */
class Auth extends Facade
{
    public static function getFacadeAccessor(): string
    {
        return 'auth';  // Resolve app('auth') → AuthManager
    }
}

Accessor como String

return 'cache';
// → Container::get('cache')

Accessor como Classe/Interface

return QueueManagerInterface::class;
// → Container::make (...)

Testing com Facades

spy() — Verificar chamadas

test('cache is called', function() {
    Cache::spy();

    $service->process();

    Cache::shouldHaveReceived('put')->once();
});

mock() — Retornos falsos

test('mocked cache', function() {
    Cache::mock()
        ->shouldReceive('get')
        ->with('key')
        ->andReturn('mocked');
});

swap() — Substituir serviço

test('with fake', function() {
    Cache::swap(new FakeCacheManager());
    // Agora usa FakeCacheManager
});

Http::fake() — Fake requests

test('api call', function() {
    Http::fake([
        'api.example.com/*' =>
            Http::response(['data' => 'mocked'])
    ]);
});

Relação com Container: Facades são uma camada de "açúcar sintático" sobre o Container DI. Cada Facade resolve um serviço registado via Service Provider.