Laravel Strategy Pattern

Use the Strategy pattern to select behavior at runtime; bind multiple implementations to a shared interface

noartem 598f78b 712 B Updated

File contents

Strategy Pattern

Create a common interface and multiple implementations. Choose a strategy by key or context.

interface TaxCalculator { public function for(int $cents): int; }
final class NzTax implements TaxCalculator { /* ... */ }
final class AuTax implements TaxCalculator { /* ... */ }

final class TaxFactory {
  public function __construct(private array $drivers) {}
  public function forCountry(string $code): TaxCalculator { return $this->drivers[$code]; }
}

Register in a service provider and inject the factory where needed.

noartem/laravel-vue-skills/tree/main/skills/laravel-strategy-pattern commit 598f78be58

Frequently asked questions

npx skillmds@latest add noartem/laravel-strategy-pattern