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.
Featured Examples โ
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:
// 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:
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:
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:
// 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? โ
- Start with Blog Content Moderation
- Practice with User Account Validation
- Try Email Campaign Targeting
Ready for Real-World Scenarios? โ
- Tackle E-commerce Discount Engine
- Explore Inventory Management
- Build Report Generation System
Want Advanced Patterns? โ
- Master Multi-tenant Authorization
- Challenge yourself with Financial Risk Assessment
- Complete Distributed Workflow Engine
Ready to see specifications in action? Choose your starting point and begin transforming your business logic!