A Laravel package for quickly generating design pattern boilerplate code. Stop writing repetitive pattern structures and focus on implementing your business logic!
- 5 Design Patterns Supported: Adapter, Strategy, Decorator, Factory, Observer
- Artisan Commands: Simple, intuitive commands for each pattern
- Smart Auto-Detection: Automatically detects Models, Services, Repositories
- Customizable Namespaces: Use custom namespaces for generated files
- Separate Files: Interface and implementation files generated separately
- Laravel Integration: Full Laravel service provider integration
Install the package via Composer:
composer require heyosseus/laravel-pattern-makerThe package will automatically register its service provider thanks to Laravel's auto-discovery.
| Pattern | Command | Description |
|---|---|---|
| Adapter | pattern:adapter |
Wrap external classes with unified interface |
| Strategy | pattern:strategy |
Switch between algorithms at runtime |
| Decorator | pattern:decorator |
Add responsibilities to objects dynamically |
| Factory | pattern:factory |
Create objects without specifying exact class |
| Observer | pattern:observer |
Notify multiple objects about state changes |
Purpose: Allows incompatible interfaces to work together. Perfect for integrating third-party libraries or services.
php artisan pattern:adapter {AdapterName} {AdapteeClass}Adapt a Service:
php artisan pattern:adapter PaymentAdapter StripeServiceResult: Imports App\Services\StripeService
Adapt a Model:
php artisan pattern:adapter UserAdapter UserResult: Imports App\Models\User
Adapt External Library:
php artisan pattern:adapter GuzzleAdapter GuzzleHttp\\ClientResult: Imports GuzzleHttp\Client
app/Patterns/Adapter/PaymentAdapterInterface.phpapp/Patterns/Adapter/PaymentAdapter.php
php artisan pattern:adapter PaymentAdapter StripeService --namespace=App\\Infrastructure\\Adaptersuse App\Patterns\Adapter\PaymentAdapterInterface;
class OrderService
{
public function __construct(private PaymentAdapterInterface $paymentAdapter) {}
public function processPayment($amount)
{
return $this->paymentAdapter->handle($amount);
}
}Purpose: Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime.
php artisan pattern:strategy {ContextName} {Strategy1?} {Strategy2?} ...Payment Strategies:
php artisan pattern:strategy Payment CreditCardStrategy PayPalStrategy CryptoStrategyNotification Strategies:
php artisan pattern:strategy Notification EmailStrategy SmsStrategy PushStrategyCreate Context Only:
php artisan pattern:strategy ShippingThen add strategies later:
php artisan pattern:strategy Shipping StandardShipping ExpressShippingapp/Patterns/Strategy/PaymentStrategyInterface.phpapp/Patterns/Strategy/PaymentContext.phpapp/Patterns/Strategy/CreditCardStrategy.phpapp/Patterns/Strategy/PayPalStrategy.phpapp/Patterns/Strategy/CryptoStrategy.php
use App\Patterns\Strategy\PaymentContext;
use App\Patterns\Strategy\CreditCardStrategy;
use App\Patterns\Strategy\PayPalStrategy;
class PaymentService
{
public function processPayment($type, $amount)
{
$strategy = match($type) {
'credit_card' => new CreditCardStrategy(),
'paypal' => new PayPalStrategy(),
default => throw new \Exception('Invalid payment type')
};
$context = new PaymentContext($strategy);
return $context->executeStrategy($amount);
}
}Purpose: Attach additional responsibilities to objects dynamically without altering their structure.
php artisan pattern:decorator {BaseName} {Decorator1?} {Decorator2?} ...Notification Decorators:
php artisan pattern:decorator Notification LoggingDecorator CachingDecorator EncryptionDecoratorData Processing Decorators:
php artisan pattern:decorator DataProcessor ValidationDecorator CompressionDecoratorapp/Patterns/Decorator/NotificationComponentInterface.phpapp/Patterns/Decorator/NotificationComponent.phpapp/Patterns/Decorator/LoggingDecorator.phpapp/Patterns/Decorator/CachingDecorator.phpapp/Patterns/Decorator/EncryptionDecorator.php
use App\Patterns\Decorator\NotificationComponent;
use App\Patterns\Decorator\LoggingDecorator;
use App\Patterns\Decorator\CachingDecorator;
// Base notification
$notification = new NotificationComponent();
// Add logging
$notification = new LoggingDecorator($notification);
// Add caching
$notification = new CachingDecorator($notification);
// Execute with all decorators
$result = $notification->operation($data);Purpose: Create objects without specifying the exact class to create. Useful for creating families of related objects.
php artisan pattern:factory {FactoryName} {Product1?} {Product2?} ...Vehicle Factory:
php artisan pattern:factory Vehicle Car Bike TruckDatabase Connection Factory:
php artisan pattern:factory Database MySQL PostgreSQL SQLiteReport Factory:
php artisan pattern:factory Report PDFReport ExcelReport CSVReportapp/Patterns/Factory/VehicleFactoryInterface.phpapp/Patterns/Factory/VehicleFactory.phpapp/Patterns/Factory/Car.phpapp/Patterns/Factory/Bike.phpapp/Patterns/Factory/Truck.php
use App\Patterns\Factory\VehicleFactory;
class TransportService
{
public function __construct(private VehicleFactory $vehicleFactory) {}
public function createVehicle($type)
{
return $this->vehicleFactory->create($type);
}
}
// Usage
$factory = new VehicleFactory();
$car = $factory->create('Car');
$bike = $factory->create('Bike');Purpose: Define a one-to-many dependency between objects so that when one object changes state, all dependents are notified.
php artisan pattern:observer {SubjectName} {Observer1?} {Observer2?} ...Order Events:
php artisan pattern:observer Order EmailObserver LogObserver InventoryObserverUser Registration:
php artisan pattern:observer User WelcomeEmailObserver ProfileSetupObserver AnalyticsObserverFile Upload:
php artisan pattern:observer FileUpload VirusScanObserver ThumbnailObserverapp/Patterns/Observer/OrderObserverInterface.phpapp/Patterns/Observer/OrderSubject.phpapp/Patterns/Observer/EmailObserver.phpapp/Patterns/Observer/LogObserver.phpapp/Patterns/Observer/InventoryObserver.php
use App\Patterns\Observer\OrderSubject;
use App\Patterns\Observer\EmailObserver;
use App\Patterns\Observer\LogObserver;
use App\Patterns\Observer\InventoryObserver;
class OrderService
{
private OrderSubject $subject;
public function __construct()
{
$this->subject = new OrderSubject();
// Attach observers
$this->subject->attach(new EmailObserver());
$this->subject->attach(new LogObserver());
$this->subject->attach(new InventoryObserver());
}
public function createOrder($orderData)
{
// Create order logic here
$order = Order::create($orderData);
// Notify all observers
$this->subject->notify(['order' => $order]);
return $order;
}
}# Create adapters for different payment providers
php artisan pattern:adapter StripeAdapter Stripe\\StripeClient
php artisan pattern:adapter PayPalAdapter PayPalCheckoutSdk\\Core\\PayPalHttpClient
php artisan pattern:adapter SquareAdapter SquareConnect\\Client
# Create strategy for payment processing
php artisan pattern:strategy Payment StripeStrategy PayPalStrategy SquareStrategy# Create observer for user events
php artisan pattern:observer User EmailObserver SmsObserver PushObserver SlackObserver
# Create decorator for notification enhancement
php artisan pattern:decorator Notification LoggingDecorator RetryDecorator RateLimitDecorator# Create adapters for different storage providers
php artisan pattern:adapter S3Adapter Aws\\S3\\S3Client
php artisan pattern:adapter GoogleAdapter Google\\Cloud\\Storage\\StorageClient
# Create factory for file processors
php artisan pattern:factory FileProcessor ImageProcessor VideoProcessor DocumentProcessor# Create strategy for different log formats
php artisan pattern:strategy Logger JsonLogger XMLLogger PlainTextLogger
# Create decorator for log enhancement
php artisan pattern:decorator Logger TimestampDecorator ContextDecorator EncryptionDecoratorAll commands support custom namespaces:
php artisan pattern:adapter PaymentAdapter StripeService --namespace=App\\Infrastructure\\Adapters
php artisan pattern:strategy Payment CreditCard --namespace=App\\Domain\\Strategies
php artisan pattern:decorator Notification Logging --namespace=App\\Services\\Decorators
php artisan pattern:factory Vehicle Car --namespace=App\\Factories
php artisan pattern:observer User Email --namespace=App\\Events\\ObserversThe package automatically detects and imports classes based on naming conventions:
- Services:
PaymentService→App\Services\PaymentService - Repositories:
UserRepository→App\Repositories\UserRepository - Models:
User→App\Models\User - Full Paths:
Vendor\Package\Class→ Uses as-is
app/
└── Patterns/
├── Adapter/
│ ├── PaymentAdapterInterface.php
│ └── PaymentAdapter.php
├── Strategy/
│ ├── PaymentStrategyInterface.php
│ ├── PaymentContext.php
│ └── CreditCardStrategy.php
├── Decorator/
│ ├── NotificationComponentInterface.php
│ ├── NotificationComponent.php
│ └── LoggingDecorator.php
├── Factory/
│ ├── VehicleFactoryInterface.php
│ ├── VehicleFactory.php
│ └── Car.php
└── Observer/
├── OrderObserverInterface.php
├── OrderSubject.php
└── EmailObserver.php
After generating patterns, you should write tests for your implementations:
// tests/Unit/Patterns/Adapter/PaymentAdapterTest.php
class PaymentAdapterTest extends TestCase
{
public function test_payment_adapter_processes_payment()
{
$mockService = Mockery::mock(StripeService::class);
$adapter = new PaymentAdapter($mockService);
$mockService->shouldReceive('handle')
->with(100)
->once()
->andReturn(['status' => 'success']);
$result = $adapter->handle(100);
$this->assertEquals(['status' => 'success'], $result);
}
}- Adapter: Adapter Pattern
- Strategy: Strategy Pattern
- Decorator: Decorator Pattern
- Factory: Factory Pattern
- Observer: Observer Pattern
Contributions are welcome! Please feel free to submit a Pull Request.
- Builder Pattern
- Command Pattern
- Repository Pattern
- Singleton Pattern
- Proxy Pattern
- Chain of Responsibility
- Template Method
- Clone the repository
- Install dependencies:
composer install - Run tests:
composer test
- PHP ^8.0|^8.1|^8.2|^8.3
- Laravel ^9.0|^10.0|^11.0|^12.0
We use SemVer for versioning. For the versions available, see the tags on this repository.
- Initial release
- Added Adapter Pattern support
- Added Strategy Pattern support
- Added Decorator Pattern support
- Added Factory Pattern support
- Added Observer Pattern support
- Smart class detection for Models, Services, Repositories
- Separate interface and implementation files
- Custom namespace support
- Author: Rati Rukhadze
- Contributors: See contributors list
The MIT License (MIT). Please see License File for more information.
If you find this package helpful, please consider:
- ⭐ Starring the repository
- 🐛 Reporting bugs
- 💡 Suggesting new features
- 📖 Improving documentation
- More design patterns
- IDE integration and snippets
- Pattern validation and suggestions
- Performance optimizations
- Enhanced documentation and examples
Happy coding with design patterns! 🎉