Subscribe to PHP Freaks RSS

StarTutorial.com: Understanding Design Patterns - Composite

syndicated from www.phpdeveloper.org on June 29, 2018

The StarTutorial site is back with the latest installment of their series covering common design patterns and their use in PHP. In this latest tutorial they cover the Composite pattern.

[The Composite pattern] allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

In their example, they tell a story about a Walmart worker that received comments from her manager about an issue with the number of cars per box. They define classes for each (Agnes, a Box and a Product), including basic functionality in each. They talk about possible ways to solve the "number of cars" problem in the code including conditional statements and other logic. This is pushed aside when a more sustainable solution is desired, one that makes use of common interfaces for multiple product types. The code examples for this new "composed" structure is included.