HomePHP Page 2 - Object Interaction in PHP: Introduction to Composition
Composition: some theory ahead - PHP
Composition is an important concept in PHP. It occurs when an object creates another object; that is, the first object completely possesses the second object. In this article (the first of two parts), Alejandro Gervasio explains composition, and shows some examples to illustrate his points.
As I mentioned before, composition is very a useful thing when applied in production environments. But, let’s dig a bit into its theory, in order to understand how can it be implemented in real-world projects. I promise it will be short.
Composition happens when one object directly creates a second object. This means that the original object is responsible for the “birth” of the second, to express it in a comprehensible way. If we think about the concept, this condition can happen many times during the execution of PHP applications. However, sometimes, when we’re working extensively with objects here and there, we might get quickly confused by having so many definitions to deal with.
As a general rule, particularly in terms of practical implementation, it’s important to know how to define a relationship between objects. Therefore, we might say that one object “composes” another one when this object is not capable of living without the other. Let’s put it in a practical way. Having two objects A and B, if our object B simply “passes away” when object A dies, then we say that object B composes to A.
Explained in that manner, you shouldn’t have a problem understanding composition. In general terms, composition is easier to handle under certain conditions where many classes are involved. The main reason for having this advantage is that, most of the time, we know which class is directly responsible for creating a specific object. The process makes it a lot easier to track the existence and usage of an object, since one particular class is directly generating another object.
Hopefully, we’ve grasped the goodies of composition’s theory, in order to gain an intimate grounding in PHP object interaction. However, I know that you’re hungry for code. Also, I know that you want some practical examples right now! Fine, relax, that's coming. Theory is good and instructive, but we need to show composition in action, in order to taste its real power. So, just let’s flip the page and illustrate with an example of how composition works.