Composite Pattern in PHP

Previously I covered all of the creational patterns which are useful with PHP and the majority of structural patterns. One structural pattern I never covered was the Composite pattern and so that’s what I’m covering today. The purpose of this pattern is to allow trees of objects (composites) to be handled interchangeably, regardless of if the node is a branch of a leaf node. What branch and leaf nodes are is revealed below.

Let’s use a hard drive as an example, you have directories which you can think of as branches, and you have files, you can think of these as leaf nodes. Branches contain leaves just like directories contain files. Directories and files are both separate entities, but the goal of the composite pattern has them interchangeable, as always this means they should implement the same interface. Example methods that they both share include updating the owner and group, changing permissions, fetching size, created date or last modified date, etc.

Continue reading

Flyweight pattern in PHP

The flyweight pattern is todays structural pattern of the day. Put simply, the flyweight pattern is used for breaking down a large domain model into a smaller domain model and a collection of tiny object-value classes called flyweights.

Flyweights can be useful when you have a collection of objects, that contain repetitive attributes and you want to share these attributes, the end goal being to save on memory usage.

Continue reading

Facade pattern in PHP

The facade pattern is today’s structural design pattern. My previous two blogs were about the adapter and the decorator patterns and just like these pattern, the facade pattern is also a known as a wrapper.

The facade pattern does have some similarities to the adapter pattern, in that they’re both used to modify the interface of an entity. However the decorator pattern is used in a very different manner. In case you forgot, here is a quick run down.

Pattern Purpose
Adapter Used to allow incompatible interfaces to work together.
Decorator Allows behaviours to be added to an object, without modifying the original class.
Facade Provides a simplified interface to a more complex library.

Continue reading

Decorator pattern in PHP

The decorator pattern is another structural pattern. The aim of the decorator pattern is to extend an existing classes functionality without modifying existing classes and rather using composition to wrap and extend the existing functionality.

Using Decorators, existing behaviours will stay the same, but you will have additional behaviour extensions which can be used to modify the output.

Continue reading