Download the PHP package cmatosbc/desired-patterns without Composer
On this page you can find all versions of the php package cmatosbc/desired-patterns. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download cmatosbc/desired-patterns
More information about cmatosbc/desired-patterns
Files in cmatosbc/desired-patterns
Package desired-patterns
Short Description A collection of modern PHP design patterns implemented using PHP 8.2+ features
License MIT
Informations about the package desired-patterns
Modern PHP Design Patterns
A collection of modern PHP design patterns implemented using PHP 8.2+ features. Sexier than older implementations and more readable than ever.
Requirements
- PHP 8.2 or higher
- Composer
Installation
Patterns Implemented
Quick Links:
- 1. Singleton Pattern
- 2. Multiton Pattern
- 3. Command Pattern
- 4. Chain of Responsibility Pattern
- 5. Registry Pattern
- 6. Service Locator Pattern
- 7. Specification Pattern
- 8. Strategy Pattern
- 9. State Pattern
- 10. Pipeline Pattern
- 11. Object Pool Pattern
- 12. Null Object Pattern
1. Singleton Pattern
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. Our implementation uses a trait to make it reusable.
2. Multiton Pattern
The Multiton pattern is similar to Singleton but maintains a map of named instances. This is useful when you need multiple named instances of a class.
3. Command Pattern
The Command pattern encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
4. Chain of Responsibility Pattern
The Chain of Responsibility pattern lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.
5. Registry Pattern
The Registry pattern provides a global point of access to objects or services throughout an application.
6. Service Locator Pattern
The Service Locator pattern is a design pattern used to encapsulate the processes involved in obtaining a service with a strong abstraction layer.
7. Specification Pattern
The Specification pattern is used to create business rules that can be combined using boolean logic.
8. Strategy Pattern
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it.
Real-World Examples
-
Payment Processing
- Different payment methods (Credit Card, PayPal, Cryptocurrency)
- Each payment method has its own validation and processing logic
- System can switch between payment strategies based on user selection
-
Data Export
- Multiple export formats (CSV, JSON, XML, PDF)
- Each format has specific formatting requirements
- Choose export strategy based on user preference or file type
- Shipping Calculation
- Various shipping providers (FedEx, UPS, DHL)
- Each provider has unique rate calculation algorithms
- Select provider based on destination, weight, or cost
Complete Example
9. State Pattern
The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. Our implementation provides a flexible and type-safe way to handle state transitions with context validation.
Real-World Example: Order Processing System
The State pattern is perfect for managing complex workflows like order processing. Each state encapsulates its own rules and behaviors:
-
States:
PendingState
: Initial state, validates order detailsProcessingState
: Handles payment verificationShippedState
: Manages shipping detailsDeliveredState
: Handles delivery confirmationCancelledState
: Manages order cancellation
-
Features:
- Context validation per state
- Type-safe state transitions
- State history tracking
- Fluent interface for state machine setup
-
Benefits:
- Clean separation of concerns
- Easy to add new states
- Type-safe state transitions
- Automatic context validation
- Comprehensive state history
- Use Cases:
- Order Processing Systems
- Document Workflow Management
- Game State Management
- Payment Processing
- Task Management Systems
10. Pipeline Pattern
The Pipeline pattern allows you to process data through a series of operations, where each operation takes input from the previous operation and produces output for the next one. This pattern is particularly useful for data transformation, validation, and processing workflows.
Features
- Fluent interface for operation chaining
- Built-in error handling
- Input validation
- Type-safe operations with PHP 8.2+ generics
- Side effect management
- Conditional processing
- Operation composition
Basic Usage
Advanced Usage with PipelineBuilder
The PipelineBuilder provides a more structured way to create complex pipelines with validation and error handling:
Real-World Example: Data Processing Pipeline
Here's a real-world example of using the Pipeline pattern for processing user data:
Benefits
- Separation of Concerns: Each operation in the pipeline has a single responsibility.
- Maintainability: Easy to add, remove, or modify processing steps without affecting other parts.
- Reusability: Pipeline operations can be reused across different contexts.
- Error Handling: Built-in error handling makes it easy to manage failures.
- Validation: Input validation can be added at any point in the pipeline.
- Type Safety: PHP 8.2+ generics provide type safety throughout the pipeline.
- Testability: Each operation can be tested in isolation.
Use Cases
- Data transformation and normalization
- Form validation and processing
- API request/response handling
- Image processing workflows
- ETL (Extract, Transform, Load) operations
- Document processing pipelines
- Multi-step validation processes
11. Object Pool Pattern
The Object Pool pattern manages a fixed set of reusable objects that are expensive to create or consume significant resources. Our implementation uses PHP 8.2 features for type-safe object management and automatic cleanup.
-
Key Features:
- Type-safe resource management
- Automatic resource cleanup using WeakMap
- Configurable pool sizes
- Resource validation and reset
- Usage statistics tracking
- Use Cases:
- Database connection pooling
- File handle management
- Network socket management
- Thread/Process pooling
- Memory-intensive object reuse
12. Null Object Pattern
The Null Object pattern provides an object with neutral ("null") behavior as an alternative to null references. Our implementation uses PHP 8.2 features for type-safe null handling and interface contracts.
-
Key Features:
- Type-safe null object implementation
- Interface-based contracts
- Abstract base class for null objects
- Explicit null checking through interface
- Zero-impact performance for null operations
- Use Cases:
- Optional service dependencies
- Testing and development environments
- Feature toggles and graceful degradation
- Default behavior implementation
- Error handling and logging
Testing
Run the test suite using PHPUnit :
Or run it updating the coverage report:
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
License
This library is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.