Skip to content

Advanced Examples โ€‹

For specification power users and enterprise applications

Master sophisticated specification patterns that solve complex architectural challenges. These examples demonstrate advanced integration with Laravel's ecosystem and enterprise-level design patterns.

What You'll Master โ€‹

  • ๐Ÿ—๏ธ Enterprise Architecture - Multi-tenant systems and complex hierarchies
  • ๐Ÿ”„ Advanced Integration - CQRS, Event Sourcing, and distributed systems
  • โšก Performance Optimization - Caching strategies and query optimization
  • ๐Ÿ” Security Patterns - Authorization hierarchies and access control
  • ๐Ÿงช Sophisticated Testing - Integration tests and performance benchmarks

Multi-tenant Authorization System โ€‹

Time: 2+ hours | Integration: Policies, Custom Gates, DI, Multi-tenancy

Build a sophisticated authorization system supporting multiple tenant types with complex permission hierarchies and role-based access control.

Perfect for mastering:

  • Hierarchical specification structures
  • Tenant-aware business logic
  • Advanced dependency injection patterns
  • Custom Laravel gate integration
  • Policy composition and inheritance

Financial Risk Assessment Engine โ€‹

Time: 3+ hours | Integration: External APIs, Queues, Events, Validation

Create a real-time risk assessment system integrating multiple data sources, complex business rules, and asynchronous processing with comprehensive audit trails.

Perfect for mastering:

  • External service integration patterns
  • Asynchronous specification evaluation
  • Complex validation scenarios with fallbacks
  • Event-driven architecture
  • Performance monitoring and caching

Distributed Workflow Engine โ€‹

Time: 3+ hours | Integration: State Machines, Commands, Events, Broadcasting

Implement a sophisticated workflow system with state transitions, conditional branching, and distributed processing using specification-driven business rules.

Perfect for mastering:

  • State machine integration
  • Command pattern with specifications
  • Event sourcing and CQRS patterns
  • Real-time workflow broadcasting
  • Complex business rule orchestration

Enterprise Integration Patterns โ€‹

Advanced Dependency Injection โ€‹

php
class RiskAssessmentService
{
    public function __construct(
        private CreditScoreSpecification $creditSpec,
        private IncomeVerificationSpecification $incomeSpec,
        private FraudDetectionSpecification $fraudSpec,
        private ComplianceSpecification $complianceSpec,
        private RiskCalculatorInterface $calculator
    ) {}
    
    public function assess(LoanApplication $application): RiskAssessment
    {
        $specifications = [
            'credit' => $this->creditSpec,
            'income' => $this->incomeSpec, 
            'fraud' => $this->fraudSpec,
            'compliance' => $this->complianceSpec,
        ];
        
        return $this->calculator->calculate($application, $specifications);
    }
}

Custom Gate Integration โ€‹

php
Gate::define('access-tenant-resource', function (User $user, Resource $resource) {
    $spec = app(TenantAccessSpecification::class, [
        'user' => $user,
        'tenant' => $resource->tenant
    ]);
    
    return $spec->isSatisfiedBy($resource);
});

// Usage with sophisticated authorization
if (Gate::allows('access-tenant-resource', $document)) {
    return $document->load('sensitiveData');
}

Event Sourcing Integration โ€‹

php
class SpecificationEventStore
{
    public function record(string $specificationClass, mixed $candidate, bool $result): void
    {
        SpecificationEvaluated::dispatch([
            'specification' => $specificationClass,
            'candidate_type' => get_class($candidate),
            'candidate_id' => $candidate->getKey(),
            'result' => $result,
            'timestamp' => now(),
            'context' => $this->gatherContext()
        ]);
    }
}

Performance & Scalability โ€‹

Specification Caching Strategy โ€‹

php
class CachedSpecification extends AbstractSpecification
{
    public function __construct(
        private SpecificationInterface $specification,
        private int $ttl = 3600
    ) {}
    
    public function isSatisfiedBy(mixed $candidate): bool
    {
        $cacheKey = $this->generateCacheKey($candidate);
        
        return Cache::remember($cacheKey, $this->ttl, function () use ($candidate) {
            return $this->specification->isSatisfiedBy($candidate);
        });
    }
    
    private function generateCacheKey(mixed $candidate): string
    {
        $specClass = get_class($this->specification);
        $candidateKey = $this->getCandidateKey($candidate);
        
        return "spec:{$specClass}:{$candidateKey}";
    }
}

Distributed Evaluation โ€‹

php
class DistributedSpecificationEvaluator
{
    public function evaluateAsync(
        SpecificationInterface $specification,
        Collection $candidates
    ): Promise {
        $jobs = $candidates->chunk(100)->map(function ($chunk, $index) use ($specification) {
            return new EvaluateSpecificationJob($specification, $chunk, $index);
        });
        
        return Promise::all($jobs->map(fn($job) => dispatch($job)));
    }
}

Advanced Testing Strategies โ€‹

Integration Testing โ€‹

php
class AdvancedSpecificationIntegrationTest extends TestCase
{
    use RefreshDatabase;
    
    /** @test */
    public function complex_multi_tenant_authorization_works_end_to_end()
    {
        // Setup multi-tenant scenario
        $tenant1 = Tenant::factory()->create();
        $tenant2 = Tenant::factory()->create();
        
        $admin = User::factory()->create(['role' => 'tenant_admin']);
        $admin->tenants()->attach($tenant1->id, ['role' => 'admin']);
        
        $user = User::factory()->create(['role' => 'user']);
        $user->tenants()->attach($tenant1->id, ['role' => 'member']);
        
        $resource = Resource::factory()->create(['tenant_id' => $tenant1->id]);
        
        // Test specification-driven authorization
        $spec = new TenantResourceAccessSpecification($admin, $tenant1);
        
        $this->assertTrue($spec->isSatisfiedBy($resource));
        $this->assertFalse($spec->isSatisfiedBy(
            Resource::factory()->create(['tenant_id' => $tenant2->id])
        ));
    }
    
    /** @test */
    public function risk_assessment_handles_external_service_failures()
    {
        Http::fake([
            'credit-bureau.com/api/*' => Http::response(null, 500),
            'fraud-detection.com/api/*' => Http::response(['score' => 0.2], 200)
        ]);
        
        $application = LoanApplication::factory()->create();
        $service = app(RiskAssessmentService::class);
        
        $result = $service->assess($application);
        
        // Should handle partial failures gracefully
        $this->assertInstanceOf(RiskAssessment::class, $result);
        $this->assertTrue($result->hasPartialData());
        $this->assertFalse($result->isComplete());
    }
}

Performance Benchmarking โ€‹

php
class SpecificationPerformanceTest extends TestCase
{
    /** @test */
    public function complex_specifications_perform_within_acceptable_limits()
    {
        $candidates = User::factory()->count(1000)->create();
        $spec = new ComplexCompositeSpecification();
        
        $startTime = microtime(true);
        
        $results = $candidates->filter(fn($user) => $spec->isSatisfiedBy($user));
        
        $executionTime = microtime(true) - $startTime;
        
        $this->assertLessThan(2.0, $executionTime, 'Specification evaluation took too long');
        $this->assertGreaterThan(0, $results->count(), 'No results found');
    }
}

Prerequisites โ€‹

  • Advanced Laravel Knowledge: Deep understanding of service container, events, queues
  • Design Patterns: Familiarity with Enterprise Application Architecture patterns
  • Database Skills: Complex queries, indexing strategies, performance optimization
  • Testing Experience: Integration testing, mocking external services
  • Architecture Understanding: Microservices, distributed systems, CQRS concepts

Learning Path โ€‹

For Experienced Developers โ€‹

  1. Start with: Multi-tenant Authorization - Complex but foundational
  2. Scale up to: Financial Risk Assessment - External integrations
  3. Master with: Distributed Workflow Engine - Full enterprise complexity

For Architects โ€‹

  1. Review all three examples for architectural patterns
  2. Focus on integration points and scalability concerns
  3. Consider adaptation for your specific domain requirements

Real-World Applications โ€‹

These patterns are battle-tested in:

  • Financial Services: Risk assessment, compliance checking, fraud detection
  • SaaS Platforms: Multi-tenant authorization, feature gating, usage monitoring
  • E-commerce: Complex pricing rules, inventory management, order processing
  • Healthcare: Patient eligibility, treatment protocols, regulatory compliance
  • Enterprise Software: Workflow automation, approval processes, audit requirements

Ready for the Challenge? โ€‹

These advanced examples will push your specification skills to the limit. Each represents months of real-world development condensed into comprehensive learning experiences.

Begin with Multi-tenant Auth โ†’

Released under the MIT License.