heyosseus/laravel-pattern-maker

A design pattern maker for laravel

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/heyosseus/laravel-pattern-maker

dev-main 2025-10-17 11:27 UTC

This package is auto-updated.

Last update: 2025-10-17 11:27:31 UTC


README

Latest Version on Packagist Total Downloads License

A Laravel package for quickly generating design pattern boilerplate code. Stop writing repetitive pattern structures and focus on implementing your business logic!

โœจ Features

  • 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

๐Ÿš€ Installation

Install the package via Composer:

composer require heyosseus/laravel-pattern-maker

The package will automatically register its service provider thanks to Laravel's auto-discovery.

๐Ÿ“‹ Available Commands

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

๐Ÿ› ๏ธ Usage Guide

1. Adapter Pattern

Purpose: Allows incompatible interfaces to work together. Perfect for integrating third-party libraries or services.

Basic Usage

php artisan pattern:adapter {AdapterName} {AdapteeClass}

Examples

Adapt a Service:

php artisan pattern:adapter PaymentAdapter StripeService

Result: Imports App\Services\StripeService

Adapt a Model:

php artisan pattern:adapter UserAdapter User

Result: Imports App\Models\User

Adapt External Library:

php artisan pattern:adapter GuzzleAdapter GuzzleHttp\\Client

Result: Imports GuzzleHttp\Client

Generated Files

  • app/Patterns/Adapter/PaymentAdapterInterface.php
  • app/Patterns/Adapter/PaymentAdapter.php

Custom Namespace

php artisan pattern:adapter PaymentAdapter StripeService --namespace=App\\Infrastructure\\Adapters

Usage Example

use App\Patterns\Adapter\PaymentAdapterInterface;

class OrderService
{
    public function __construct(private PaymentAdapterInterface $paymentAdapter) {}

    public function processPayment($amount)
    {
        return $this->paymentAdapter->handle($amount);
    }
}

2. Strategy Pattern

Purpose: Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime.

Basic Usage

php artisan pattern:strategy {ContextName} {Strategy1?} {Strategy2?} ...

Examples

Payment Strategies:

php artisan pattern:strategy Payment CreditCardStrategy PayPalStrategy CryptoStrategy

Notification Strategies:

php artisan pattern:strategy Notification EmailStrategy SmsStrategy PushStrategy

Create Context Only:

php artisan pattern:strategy Shipping

Then add strategies later:

php artisan pattern:strategy Shipping StandardShipping ExpressShipping

Generated Files

  • app/Patterns/Strategy/PaymentStrategyInterface.php
  • app/Patterns/Strategy/PaymentContext.php
  • app/Patterns/Strategy/CreditCardStrategy.php
  • app/Patterns/Strategy/PayPalStrategy.php
  • app/Patterns/Strategy/CryptoStrategy.php

Usage Example

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);
    }
}

3. Decorator Pattern

Purpose: Attach additional responsibilities to objects dynamically without altering their structure.

Basic Usage

php artisan pattern:decorator {BaseName} {Decorator1?} {Decorator2?} ...

Examples

Notification Decorators:

php artisan pattern:decorator Notification LoggingDecorator CachingDecorator EncryptionDecorator

Data Processing Decorators:

php artisan pattern:decorator DataProcessor ValidationDecorator CompressionDecorator

Generated Files

  • app/Patterns/Decorator/NotificationComponentInterface.php
  • app/Patterns/Decorator/NotificationComponent.php
  • app/Patterns/Decorator/LoggingDecorator.php
  • app/Patterns/Decorator/CachingDecorator.php
  • app/Patterns/Decorator/EncryptionDecorator.php

Usage Example

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);

4. Factory Pattern

Purpose: Create objects without specifying the exact class to create. Useful for creating families of related objects.

Basic Usage

php artisan pattern:factory {FactoryName} {Product1?} {Product2?} ...

Examples

Vehicle Factory:

php artisan pattern:factory Vehicle Car Bike Truck

Database Connection Factory:

php artisan pattern:factory Database MySQL PostgreSQL SQLite

Report Factory:

php artisan pattern:factory Report PDFReport ExcelReport CSVReport

Generated Files

  • app/Patterns/Factory/VehicleFactoryInterface.php
  • app/Patterns/Factory/VehicleFactory.php
  • app/Patterns/Factory/Car.php
  • app/Patterns/Factory/Bike.php
  • app/Patterns/Factory/Truck.php

Usage Example

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');

5. Observer Pattern

Purpose: Define a one-to-many dependency between objects so that when one object changes state, all dependents are notified.

Basic Usage

php artisan pattern:observer {SubjectName} {Observer1?} {Observer2?} ...

Examples

Order Events:

php artisan pattern:observer Order EmailObserver LogObserver InventoryObserver

User Registration:

php artisan pattern:observer User WelcomeEmailObserver ProfileSetupObserver AnalyticsObserver

File Upload:

php artisan pattern:observer FileUpload VirusScanObserver ThumbnailObserver

Generated Files

  • app/Patterns/Observer/OrderObserverInterface.php
  • app/Patterns/Observer/OrderSubject.php
  • app/Patterns/Observer/EmailObserver.php
  • app/Patterns/Observer/LogObserver.php
  • app/Patterns/Observer/InventoryObserver.php

Usage Example

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;
    }
}

๐ŸŽฏ Real-World Use Cases

Payment Gateway Integration

# 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

Notification System

# 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

File Storage System

# 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

Logging System

# 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 EncryptionDecorator

๐Ÿ”ง Advanced Features

Custom Namespaces

All 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\\Observers

Smart Class Detection

The 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

Generated File Structure

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

๐Ÿงช Testing

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);
    }
}

๐Ÿ“š Learning Resources

Design Patterns Explained

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Ideas for New Patterns

  • Builder Pattern
  • Command Pattern
  • Repository Pattern
  • Singleton Pattern
  • Proxy Pattern
  • Chain of Responsibility
  • Template Method

Development Setup

  1. Clone the repository
  2. Install dependencies: composer install
  3. Run tests: composer test

๐Ÿ“„ Requirements

  • PHP ^8.0|^8.1|^8.2|^8.3
  • Laravel ^9.0|^10.0|^11.0|^12.0

๐Ÿท๏ธ Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

๐Ÿ“ Changelog

v1.0.0 (2025-10-17)

  • 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

๐Ÿ‘จโ€๐Ÿ’ป Credits

๐Ÿ“„ License

The MIT License (MIT). Please see License File for more information.

๐ŸŒŸ Support

If you find this package helpful, please consider:

๐Ÿš€ What's Next?

  • More design patterns
  • IDE integration and snippets
  • Pattern validation and suggestions
  • Performance optimizations
  • Enhanced documentation and examples

Happy coding with design patterns! ๐ŸŽ‰