PHP DESIGN
PATTERNS SINGELTON
Practical Cheat Sheet
When: 1 and only 1 instance of a Usage
www.ApplicableProgramming.com class. config
database instance
Drawbacks: antipattern, breaks file instance
MVC Shared resources
good practice, difficult to test,
global state global state
management
When: Separation of concerns in UI
applications by splitting application in three
main areas.
Usage: Web applications, GUI frameworks. Reference code
Key: Model <-> View <-> Controller
Model: Data & logic
View: UI representation
Controller: User input handling
ADAPTER DEPENDENCY INJECTION:
When: a class needs to use another class - Reduce tight
When: Make different interfaces work together.
coupling between classes
Adapt one interface to already existing
Usage: controllers, services etc. Improve modularity, enable
ecosystem.
testing
Usage: Integrate legacy or external systems,
Key: Inject dependencies via constructor or setter
refactor code.
Reference code:
Drawbacks: Increased vode complexity
ACTIVE RECORD - OBJECT
SIMPLE FACTORY
RELATION MAPPER
Problem: Simplify CRUD operations with a database.
Problem: Decouple object creation from its usage.
Usage: Object-relational mapping, data access.
Hide complex object creation or configuration from
Key: Model (represents table)
the object consumer.
Usage: Flexible and dynamic object instantiation.
Key: Creator <-> Product
Drawbacks: Limited flexibility (one-to-one mapping
with database tables). Can lead to "fat models"
(models with too much logic). Difficult with exceptions
to the main functionality.
Drawbacks: Code complexity: (additional classes or
interfaces). Requires subclassing to create new
products
FACADE
Problem: Simplify complex operations with a unified
interface. (usually operations that include multiple
objects or classes)
Usage: Hide implementation details, simplifies OBSERVER
usage.
Problem: communication between many objects
(that could also be missing from the system).
Usage: Event handling, plugins, dynamic codebase.
Key: Subject <-> Observer
Drawbacks: May hide necessary details in some Drawbacks: Memory leaks (if observers aren't
cases, additional layer detached), performance issues (with many observers)
DECORATOR STRATEGY
Problem: Add or change functionality to objects Problem: changing different algorithms at runtime.
dynamically during runtime, in different combinations Usage: different services
Usage: Unpredictable combination of changes Key: Context <-> Strategy
(products, services doing calculations)
Key: Decorator <-> Component
Drawbacks: Code complexity, difficult testing,
Potential performance overhead (multiple layers of Drawbacks: Increased number of objects (one per
decoration). strategy).