PHPackages                             heyosseus/laravel-pattern-maker - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. heyosseus/laravel-pattern-maker

ActiveLibrary

heyosseus/laravel-pattern-maker
===============================

A design pattern maker for laravel

00PHP

Since Oct 17Pushed 6mo agoCompare

[ Source](https://github.com/Heyosseus/laravel-pattern-maker)[ Packagist](https://packagist.org/packages/heyosseus/laravel-pattern-maker)[ RSS](/packages/heyosseus-laravel-pattern-maker/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Pattern Maker
=====================

[](#laravel-pattern-maker)

[![Latest Version on Packagist](https://camo.githubusercontent.com/949c542041281567040fe073367b696a964d991e8d6e96c19430bb01d0c9a65f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6865796f73736575732f6c61726176656c2d7061747465726e2d6d616b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/heyosseus/laravel-pattern-maker)[![Total Downloads](https://camo.githubusercontent.com/756244fbed13da540cb1d8398288e2dbf0c6909635b51cf0b8cd12a36d7c420f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6865796f73736575732f6c61726176656c2d7061747465726e2d6d616b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/heyosseus/laravel-pattern-maker)[![License](https://camo.githubusercontent.com/04b5aa91f869ecb2c1db313abe4ab4e986641a063f8b7d295af9c9f854299625/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6865796f73736575732f6c61726176656c2d7061747465726e2d6d616b65722e7376673f7374796c653d666c61742d737175617265)](LICENSE)

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

✨ Features
----------

[](#-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
--------------

[](#-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
--------------------

[](#-available-commands)

PatternCommandDescriptionAdapter`pattern:adapter`Wrap external classes with unified interfaceStrategy`pattern:strategy`Switch between algorithms at runtimeDecorator`pattern:decorator`Add responsibilities to objects dynamicallyFactory`pattern:factory`Create objects without specifying exact classObserver`pattern:observer`Notify multiple objects about state changes🛠️ Usage Guide
--------------

[](#️-usage-guide)

### 1. Adapter Pattern

[](#1-adapter-pattern)

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

#### Basic Usage

[](#basic-usage)

```
php artisan pattern:adapter {AdapterName} {AdapteeClass}
```

#### Examples

[](#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

[](#generated-files)

- `app/Patterns/Adapter/PaymentAdapterInterface.php`
- `app/Patterns/Adapter/PaymentAdapter.php`

#### Custom Namespace

[](#custom-namespace)

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

#### Usage Example

[](#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

[](#2-strategy-pattern)

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

#### Basic Usage

[](#basic-usage-1)

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

#### Examples

[](#examples-1)

**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

[](#generated-files-1)

- `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

[](#usage-example-1)

```
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

[](#3-decorator-pattern)

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

#### Basic Usage

[](#basic-usage-2)

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

#### Examples

[](#examples-2)

**Notification Decorators:**

```
php artisan pattern:decorator Notification LoggingDecorator CachingDecorator EncryptionDecorator
```

**Data Processing Decorators:**

```
php artisan pattern:decorator DataProcessor ValidationDecorator CompressionDecorator
```

#### Generated Files

[](#generated-files-2)

- `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

[](#usage-example-2)

```
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

[](#4-factory-pattern)

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

#### Basic Usage

[](#basic-usage-3)

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

#### Examples

[](#examples-3)

**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

[](#generated-files-3)

- `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

[](#usage-example-3)

```
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

[](#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

[](#basic-usage-4)

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

#### Examples

[](#examples-4)

**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

[](#generated-files-4)

- `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

[](#usage-example-4)

```
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
----------------------

[](#-real-world-use-cases)

### Payment Gateway Integration

[](#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

[](#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

[](#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

[](#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
-------------------

[](#-advanced-features)

### Custom Namespaces

[](#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

[](#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

[](#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
---------

[](#-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
--------------------

[](#-learning-resources)

### Design Patterns Explained

[](#design-patterns-explained)

- **Adapter**: [Adapter Pattern](https://refactoring.guru/design-patterns/adapter)
- **Strategy**: [Strategy Pattern](https://refactoring.guru/design-patterns/strategy)
- **Decorator**: [Decorator Pattern](https://refactoring.guru/design-patterns/decorator)
- **Factory**: [Factory Pattern](https://refactoring.guru/design-patterns/factory-method)
- **Observer**: [Observer Pattern](https://refactoring.guru/design-patterns/observer)

🤝 Contributing
--------------

[](#-contributing)

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

### Ideas for New Patterns

[](#ideas-for-new-patterns)

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

### Development Setup

[](#development-setup)

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

📄 Requirements
--------------

[](#-requirements)

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

🏷️ Versioning
-------------

[](#️-versioning)

We use [SemVer](https://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/Heyosseus/laravel-pattern-maker/tags).

📝 Changelog
-----------

[](#-changelog)

### v1.0.0 (2025-10-17)

[](#v100-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
-----------

[](#‍-credits)

- **Author**: [Rati Rukhadze](https://github.com/Heyosseus)
- **Contributors**: See [contributors list](https://github.com/Heyosseus/laravel-pattern-maker/contributors)

📄 License
---------

[](#-license)

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

🌟 Support
---------

[](#-support)

If you find this package helpful, please consider:

- ⭐ Starring the repository
- 🐛 [Reporting bugs](https://github.com/Heyosseus/laravel-pattern-maker/issues)
- 💡 [Suggesting new features](https://github.com/Heyosseus/laravel-pattern-maker/issues)
- 📖 Improving documentation

🚀 What's Next?
--------------

[](#-whats-next)

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

---

**Happy coding with design patterns!** 🎉

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance48

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/563a5f53145ba4bd3fd5b90546b8996ef2018002999533e3ea0bfefde52ff0a2?d=identicon)[Heyosseus](/maintainers/Heyosseus)

---

Top Contributors

[![Heyosseus](https://avatars.githubusercontent.com/u/102967865?v=4)](https://github.com/Heyosseus "Heyosseus (1 commits)")

---

Tags

artisanboilerplatedesign-patternsdeveloper-toolslaravelphp

### Embed Badge

![Health badge](/badges/heyosseus-laravel-pattern-maker/health.svg)

```
[![Health](https://phpackages.com/badges/heyosseus-laravel-pattern-maker/health.svg)](https://phpackages.com/packages/heyosseus-laravel-pattern-maker)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
