Skip to content

Real-World Examples โ€‹

Learn through complete refactoring scenarios. See how specifications transform messy business logic into clean, maintainable code through actual code examples from real applications.

What You'll Find Here โ€‹

This section provides complete, step-by-step refactoring examples showing:

  • ๐Ÿ” Business Logic Recognition - How to spot scattered rules
  • ๐ŸŽฏ Specification Strategy - Choosing the right specification approach
  • โš’๏ธ Implementation Process - Using Artisan commands and patterns
  • ๐Ÿงช Testing Setup - Unit testing and Pest integration
  • ๐Ÿ—๏ธ Advanced Integration - Validation, middleware, DI, and more

Example Categories โ€‹

๐ŸŸข Basic Examples โ€‹

Perfect for developers new to specifications. Complete walkthroughs showing the entire process from problem identification to testing.

๐ŸŸก Intermediate Examples โ€‹

Real-world scenarios with moderate complexity. Shows integration with Laravel features and multiple specification composition.

๐Ÿ”ด Advanced Examples โ€‹

Complex business scenarios for power users. Demonstrates advanced patterns, custom integrations, and sophisticated testing strategies.

Blog Content Moderation System โ€‹

Difficulty: Basic | Integration: Validation, Events

Transform a messy content approval system into clean, testable specifications. Includes complete testing setup with Pest.

You'll Learn:

  • Recognizing complex conditional logic
  • Creating multiple focused specifications
  • Event-driven specification triggers
  • Comprehensive test coverage

E-commerce Discount Engine โ€‹

Difficulty: Intermediate | Integration: Collections, Caching, Middleware

Refactor a complex discount calculation system with multiple business rules, seasonal promotions, and user eligibility requirements.

You'll Learn:

  • Specification composition strategies
  • Performance optimization with caching
  • Middleware integration for access control
  • Dynamic rule loading

Multi-tenant Authorization System โ€‹

Difficulty: Advanced | Integration: Policies, DI, Custom Gates

Build a sophisticated authorization system supporting multiple tenant types with complex permission hierarchies.

You'll Learn:

  • Advanced specification hierarchies
  • Dependency injection patterns
  • Custom Laravel gate integration
  • Multi-context specification design

Financial Risk Assessment โ€‹

Difficulty: Advanced | Integration: External APIs, Queues, Validation

Create a real-time risk assessment system integrating multiple data sources and complex business rules.

You'll Learn:

  • External service integration
  • Asynchronous specification evaluation
  • Complex validation scenarios
  • Error handling and fallbacks

Integration Showcases โ€‹

Validation Integration โ€‹

See how specifications work seamlessly with Laravel's validation system:

php
// Custom validation rule using specifications
class SpecificationRule implements Rule
{
    public function __construct(
        private SpecificationInterface $specification
    ) {}
    
    public function passes($attribute, $value): bool
    {
        return $this->specification->isSatisfiedBy($value);
    }
}

// Usage in Form Request
$rules['user'] = ['required', new SpecificationRule(new EligibleUserSpecification())];

Middleware Integration โ€‹

Protect routes with specification-based middleware:

php
class SpecificationMiddleware
{
    public function handle(Request $request, Closure $next, string $specClass): Response
    {
        $spec = app($specClass);
        
        if (!$spec->isSatisfiedBy($request->user())) {
            abort(403, 'Access denied');
        }
        
        return $next($request);
    }
}

// Usage
Route::middleware(['specification:PremiumUserSpecification'])
    ->get('/premium-content', PremiumController::class);

Dependency Injection โ€‹

Leverage Laravel's container for clean specification injection:

php
class SubscriptionService
{
    public function __construct(
        private EligibleForUpgradeSpecification $upgradeSpec,
        private PaymentValidSpecification $paymentSpec
    ) {}
    
    public function processUpgrade(User $user, array $paymentData): bool
    {
        if (!$this->upgradeSpec->isSatisfiedBy($user)) {
            throw new UpgradeNotAllowedException();
        }
        
        if (!$this->paymentSpec->isSatisfiedBy($paymentData)) {
            throw new InvalidPaymentException();
        }
        
        return $this->executeUpgrade($user, $paymentData);
    }
}

Before You Start โ€‹

Prerequisites โ€‹

  • Laravel 9+ application
  • Laravel Specifications package installed
  • Basic understanding of Laravel concepts
  • PHPUnit or Pest for testing

Example Code Repository โ€‹

All examples include complete, runnable code available at: github.com/dangerwayne/laravel-specifications-examples

Testing Setup โ€‹

Examples use both PHPUnit and Pest. Choose your preferred testing framework:

php
// PHPUnit style
class SpecificationTest extends TestCase
{
    public function test_specification_behavior(): void
    {
        $spec = new MySpecification();
        $this->assertTrue($spec->isSatisfiedBy($candidate));
    }
}

// Pest style
it('validates specification behavior', function () {
    $spec = new MySpecification();
    expect($spec->isSatisfiedBy($candidate))->toBeTrue();
});

Learning Path Recommendations โ€‹

New to Specifications? โ€‹

  1. Start with Blog Content Moderation
  2. Practice with User Account Validation
  3. Try Email Campaign Targeting

Ready for Real-World Scenarios? โ€‹

  1. Tackle E-commerce Discount Engine
  2. Explore Inventory Management
  3. Build Report Generation System

Want Advanced Patterns? โ€‹

  1. Master Multi-tenant Authorization
  2. Challenge yourself with Financial Risk Assessment
  3. Complete Distributed Workflow Engine

Ready to see specifications in action? Choose your starting point and begin transforming your business logic!

Start with Basic Examples โ†’

Released under the MIT License.