HomePHP Object Interaction in PHP: Introduction to Composition
Object Interaction in PHP: Introduction to Composition
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.
From a PHP programmerís point of view, there are many interesting ways that objects can interact with each other within an application. Used extensively across well-structured projects, inheritance is one of the major foundations of the object-oriented paradigm. It allows a basic and generic functionality to be implemented on a base class, and provide generic methods and properties that are inherited by any derived subclass, in order to ďfine-tuneĒ the child classes to suit more specific purposes. If youíve been working for a while with database abstraction classes, to cite an illustrative example, probably you know what Iím talking about here.
Aside from inheritance, and its partner, polymorphism, we can find other situations where objects are involved in some kind of interaction. Definitely, one concept that rapidly comes to my mind is that of aggregation. If youíre unaware of its existence, youíre missing something really relevant, trust me.
Generally speaking, aggregation occurs when one object uses the functionality of another object to satisfy its own purposes. Although this sounds a bit egotistical, the truth is that aggregation is an extremely powerful concept, used very frequently in object-oriented environments. Commonly, there are situations where one object, such as a database result set processor, needs to have database connectivity within its scope. This is a common case where this last object performs a query against a database, using the connectivity given by the first object, which is usually passed to the second as a constructor parameter.
Definitely, this might sound familiar to you, if you work with objects in PHP on a daily basis. However, the subject is really very far from being fully covered. I hope you're wondering why. What about having an object that creates another object, that is, the first object completely possesses the second? Yes! Now we are talking about a concept often known as composition.
So, do we have yet another big player in the OOP arena? You bet. Whatís more, composition plays a very important role in many situations, where the interaction between objects is carried out in a carefully planned way. Thus, the subject deserves an indepth examination. Thatís what Iíll do in the course of this article. Iíll offer a short introduction to the theory of composition, as well as its possible implementation in different practical situations. I guess that youíre ready to learn more about it, right? Okay then, letís not waste any more time in preliminaries.