---
name: architecture-32849a7d275d
description: >-
  Define a arquitetura limpa de projetos Laravel com Actions, DTOs, Policies e Service Layer. Use quando precisar organizar estrutura de diretórios, definir padrões arquiteturais, ou planejar a organização de um projeto Laravel.
compatibility: PHP 8.2+, Laravel 11+, laravel-actions
metadata:
  author: aronpc
  version: 5.0.0
  category: laravel
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
---

# architecture

## Resumo
Define e mantém arquitetura limpa em projetos Laravel usando Actions, DTOs e Policies.

## Skills Relacionadas

| Skill | Quando usar junto |
|-------|-------------------|
| `coder` | Para implementar seguindo a arquitetura |
| `actions` | Para Actions, Events e Jobs |
| `models` | Para Models e relações |
| `exceptions` | Para exceções de domínio |
| `testing` | Para testar Actions e Policies |
| `planner` | Para planejar arquitetura de features |

## Quando usar

Use esta skill sempre que:
- Criar novas features
- Estruturar código existente
- Refatorar seguindo clean architecture
- Definir responsabilidades de camadas
- Criar Actions, DTOs, ou Policies

## Stack Tecnológico

**Exemplo de stack — ajuste ao seu projeto:** Laravel 11+ + React + Inertia.js + Filament 4.x + Tailwind 4

### Pontos Chave

- **Admin Panel:** Filament 4.x (opcional)
- **Actions Pattern:** Laravel Actions (lorisleiva/laravel-actions)
- **Testing:** Pest PHP
- **i18n:** English, Spanish, Portuguese BR

## Regras de Codificação

### Core Rules

- PHP 8.2+, strict types: `declare(strict_types=1);`
- Siga pint.json, PHPStan max level
- Não use `DB::`, use `Model::query()`
- Não use `env()` fora de arquivos de configuração
- Sempre obtenha aprovação antes de novos diretórios/dependências
- Delete `.gitkeep` ao adicionar arquivos

### Laravel 11+ Específico

- Commands são registrados automaticamente de `app/Console/Commands/`
- Use `config('app.name')` não `env('APP_NAME')`

## Estrutura do Projeto

```
app/
├── Actions/          # Lógica de negócio (NÃO Services!) — subpastas por domínio (exemplos)
│   ├── Domain1/
│   ├── Domain2/
│   └── Domain3/
├── DataObjects/      # Value Objects (DTOs) — subpastas por domínio (exemplos)
│   ├── Domain1/
│   ├── Domain2/
│   └── Domain3/
├── Enums/            # Todos os enums (nomes descritivos, sem sufixo)
├── Events/           # Eventos de domínio (past tense)
├── Listeners/        # Event listeners (imperative)
├── Models/           # Eloquent models (thin, sem lógica de negócio)
├── Observers/        # Model lifecycle observers
├── Http/
│   ├── Controllers/  # Thin orchestrators
│   └── Requests/     # Form Requests (validation)
└── Policies/         # Authorization logic
```

> **Nota:** os exemplos de código nas seções a seguir usam um domínio ilustrativo (SaaS multi-tenant — `Business`, `Order`, `Tenant`) apenas para demonstração; mapeie-os aos domínios reais do seu projeto.

## Resumo de Arquitetura

Este projeto segue **clean architecture** com clara separação de responsabilidades:

```
┌─────────────────────────────────────────────────────────────┐
│                      HTTP REQUEST                            │
└──────────────────────┬──────────────────────────────────────┘
                       ↓
┌─────────────────────────────────────────────────────────────┐
│  CONTROLLER (Thin Orchestrator)                              │
│  ├─ Validate (FormRequest)                                   │
│  ├─ Authorize (Policy)                                       │
│  ├─ Build Value Object                                       │
│  └─ Call Action                                              │
└──────────────────────┬──────────────────────────────────────┘
                       ↓
┌─────────────────────────────────────────────────────────────┐
│  VALUE OBJECT (Data Transfer)                                │
│  ├─ Type-safe data structure                                 │
│  ├─ Immutable (readonly)                                     │
│  └─ Factory methods (fromRequest, toArray)                   │
└──────────────────────┬──────────────────────────────────────┘
                       ↓
┌─────────────────────────────────────────────────────────────┐
│  ACTION (Business Logic)                                     │
│  ├─ Single responsibility                                    │
│  ├─ Database operations                                      │
│  ├─ Business rules & calculations                            │
│  ├─ Call other Actions if needed                             │
│  └─ Dispatch Events                                          │
└──────────────────────┬──────────────────────────────────────┘
                       ↓
┌─────────────────────────────────────────────────────────────┐
│  MODEL (Data + Relationships)                                │
│  ├─ Eloquent relationships                                   │
│  ├─ Accessors & Mutators                                     │
│  ├─ Scopes                                                   │
│  └─ NO business logic                                        │
└──────────────────────┬──────────────────────────────────────┘
                       ↓
┌─────────────────────────────────────────────────────────────┐
│  OBSERVER / EVENT (Side Effects)                             │
│  ├─ Model lifecycle hooks (Observer)                         │
│  ├─ Send notifications                                       │
│  ├─ Update related records                                   │
│  └─ Log activities                                           │
└─────────────────────────────────────────────────────────────┘
```

## Responsabilidades de Camada

| Camada | Responsabilidade | ✅ Deve | ❌ Não Deve |
|--------|------------------|----------|---------------|
| **Controller** | Orquestração HTTP | Validate, Authorize, Delegate, Respond | Lógica de negócio, Queries de database |
| **Value Object** | Transferência de dados | Type safety, Imutabilidade | Validação, Lógica de negócio |
| **Action** | Lógica de negócio | CRUD, Cálculos, Regras, Eventos | Preocupações HTTP, Validação |
| **Model** | Dados + Relações | Relações, Casts, Scopes | Lógica de negócio, Cálculos complexos |
| **Observer** | Side effects | Lifecycle hooks, Events | Lógica de negócio core |
| **Event/Listener** | Side effects desacoplados | Notifications, Logging, Async tasks | Fluxo de negócio principal |

## Convenções de Nomenclatura

| Tipo | Convenção | Exemplo |
|------|------------|----------|
| **Enum** | Sem sufixo (Spatie) | `BusinessType`, `UserRole` |
| **Action** | Sufixo `Action` | `CreateBusinessAction`, `UpdateOrderAction` |
| **Value Object** | Sufixo `Data` | `CreateBusinessData`, `UpdateOrderData` |
| **Controller** | Plural + `Controller` | `BusinessesController`, `OrdersController` |
| **Event** | Past tense, sem sufixo | `BusinessCreated`, `OrderPlaced` |
| **Listener** | Imperativo, sem sufixo | `SendWelcomeEmail`, `NotifyAdmin` |
| **Observer** | Sufixo `Observer` | `BusinessObserver`, `OrderObserver` |
| **Policy** | Sufixo `Policy` | `BusinessPolicy`, `OrderPolicy` |
| **Form Request** | Sufixo `Request` | `StoreBusinessRequest`, `UpdateOrderRequest` |

**NOTA:** NUNCA use sufixo `Service` - use Actions!

## Comandos Comuns

### Criar Model + Migration + Factory

```bash
php artisan make:model Product -mf
```

### Criar Action

```bash
php artisan make:action CreateProduct
```

### Criar Value Object

```bash
php artisan make:class DataObjects/Product/CreateProductData
```

### Criar Form Request

```bash
php artisan make:request StoreProductRequest
```

### Criar Policy

```bash
php artisan make:policy ProductPolicy --model=Product
```

### Criar Observer

```bash
php artisan make:observer ProductObserver --model=Product
```

### Criar Test

```bash
php artisan make:test --pest ProductTest
```

## Checklist de Conclusão

Antes de finalizar QUALQUER feature:

- [ ] Testes passando (`composer test`)
- [ ] Código fixado (`composer fix`)
- [ ] Eager loading implementado (sem N+1)
- [ ] Traduções adicionadas (EN, ES, PT-BR)
- [ ] IMPLEMENTATION.md atualizado
- [ ] Documentação commitada separadamente
- [ ] Sem dependências não aprovadas

## Exemplo de Controller Thin

```php
final class BusinessController
{
    public function store(StoreBusinessRequest $request): RedirectResponse
    {
        // ✅ GOOD: Thin controller - delega para Action
        $business = CreateBusinessAction::run(
            tenant: auth()->user()->tenant,
            data: $request->validated()
        );

        return redirect()
            ->route('owner.businesses.index')
            ->with('success', __('messages.business_created'));
    }
}
```

## Exemplo de Action

```php
final class CreateBusinessAction
{
    use AsAction;

    public function handle(Tenant $tenant, CreateBusinessData $data): Business
    {
        // Check limits
        if (!$tenant->isWithinLimit('businesses')) {
            throw new BusinessLimitExceededException();
        }

        // Create business
        $business = $tenant->businesses()->create($data->toArray());

        // Increment usage
        $tenant->incrementUsage('businesses');

        // Dispatch event
        event(new BusinessCreated($business));

        return $business;
    }
}
```

## Exemplo de Value Object

```php
final readonly class CreateBusinessData
{
    public function __construct(
        public string $name,
        public string $type,
        public ?string $email = null,
        public ?string $phone = null,
    ) {}

    public static function fromRequest(array $data): self
    {
        return new self(
            name: $data['name'],
            type: $data['type'],
            email: $data['email'] ?? null,
            phone: $data['phone'] ?? null,
        );
    }

    public function toArray(): array
    {
        return [
            'name' => $this->name,
            'type' => $this->type,
            'email' => $this->email,
            'phone' => $this->phone,
        ];
    }
}
```

## Exemplo de Policy

```php
final class BusinessPolicy
{
    public function view(User $user, Business $business): bool
    {
        return $user->tenant_id === $business->tenant_id;
    }

    public function create(User $user): bool
    {
        return $user->tenant->isWithinLimit('businesses');
    }

    public function update(User $user, Business $business): bool
    {
        return $user->tenant_id === $business->tenant_id;
    }

    public function delete(User $user, Business $business): bool
    {
        return $user->tenant_id === $business->tenant_id;
    }
}
```

## Referências Cruzadas

- **Traduções**: Veja `i18n` para traduções de Enums, mensagens e interfaces
- **Exceções**: Veja `exceptions` para exceções de domínio e regras de negócio
- **Testes**: Veja `testing` para testes de Actions e Policies
- **Events/Jobs**: Veja `actions` para patterns avançados de eventos

## Referências

- [Laravel Actions](https://laravelactions.com/) - Documentação oficial do pacote
- [Laravel Docs](https://laravel.com/docs) - Documentação oficial do Laravel


---
Source attribution: aronpc
Original project: https://github.com/aronpc/ai/blob/85e01f1cbbd8159dd87c408f226435c0b3201c09/skills/architecture/SKILL.md
License: MIT
License information: https://opensource.org/license/mit
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

MIT License

Copyright (c) 2026 AronPC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.



# Mega AI Hub resource metadata

Creator / publisher: aronpc
Original project: https://github.com/aronpc/ai/blob/85e01f1cbbd8159dd87c408f226435c0b3201c09/skills/architecture/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering, Product Management
Roles: Backend Developer, Full-Stack Developer, Product Manager
Specialties: Backend
Tools: Laravel Actions
Country applicability: Country not specified
Classification basis: Source category, role and specialization labels
Instruction SHA-256: 1b2a14de64ea96705646b12f0d045feef1f44845a031c04e84780fcaf8eb9a6a
