📊 Capítulo 08: Factories, Seeders & Transações
Especialização Backend com PHP & Laravel
🗺️ Transações Atômicas com DB::transaction
flowchart TD
BEGIN["DB::transaction(function () use ($dados) { ... })"]
--> OP1["$pedido = Pedido::create($dados);"]
--> OP2["$produto->decrement('estoque', $dados['qtd']);"]
--> OP3["$gateway->cobrar();"]
--> CHECK{"Houve Exceção?"}
CHECK -- "SIM (throw new Exception)" --> ROLLBACK["Rollback Automático de TODAS as tabelas"]
CHECK -- "NÃO" --> COMMIT["Commit Garantido no Banco de Dados!"]
style BEGIN fill:#ede7f6,stroke:#512da8,stroke-width:2px
style OP1 fill:#e8f5e9,stroke:#4caf50,stroke-width:1.5px
style OP2 fill:#e8f5e9,stroke:#4caf50,stroke-width:1.5px
style OP3 fill:#e8f5e9,stroke:#4caf50,stroke-width:1.5px
style CHECK fill:#fff3e0,stroke:#ff9800,stroke-width:1.5px
style ROLLBACK fill:#ffebee,stroke:#d32f2f,stroke-width:2px
style COMMIT fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px
🎯 Slide 1: Model Factories com Faker PHP
class ProdutoFactory extends Factory {
public function definition(): array {
return [
'nome' => fake()->words(3, true),
'preco' => fake()->randomFloat(2, 10, 500),
'sku' => fake()->unique()->bothify('PROD-####'),
'ativo' => true,
];
}
}
🎯 Slide 2: Povoando Ambientes com Seeders
// Popula 100 usuários com 5 pedidos cada em 1 linha!
Usuario::factory()
->count(100)
->has(Pedido::factory()->count(5), 'pedidos')
->create();
🎯 Slide 3: Transações com Tentativas Automáticas (Deadlock Retry)
DB::transaction(callback, 5): Tenta executar a transação até 5 vezes automaticamente caso ocorra um Deadlock no PostgreSQL/MySQL!
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim