Composition and aggregation both are confusion to me. Does my code sample below indicate composition or aggregation?
class A {
public static function getData($id) {
//something
}
public static function checkUrl($url) {
// something
}
class B {
public function executePatch() {
$data = A::getData(12);
}
public function readUrl() {
$url = A::checkUrl('http/erere.com');
}
public function storeData() {
//something not related to class A at all
}
}
}
Is class B a composition of class A or is it aggregation of class A? Does composition purely mean that if class A gets deleted class B does not works at all and aggregation if class A gets deleted methods in class B that do not use class A will work?
0
The Wikipedia page on object composition might be a good starting point. Aggregation is a more general form of composition, or composition is a stronger form of aggregation. Composition is effectively an ownership relationship, while aggregation is a “contains” relationship. In composition, the parts can not exist outside the thing that contains them, but they individual things can exist on their own as unique entities in aggregation.
Your code isn’t an example of either aggregation or composition. Your class B
does not contain an instance of class A
. In addition, there’s no way to say if class A
can or can not exist without an instance of class B
. It appears that your code sample indicates that class B
is dependent on class A
, but that’s one of the weakest forms of relationship between two classes in that it is among the least descriptive of how they are structurally related.
2
In PHP 5.4 there was introduced an additional mechanism allowing composition called “traits” so your example could be something like
trait A {
public static function getData($id) {
//something
}
public static function checkUrl($url) {
// something
}
}
class B {
use A;
}
You cannot instantiate trait so
$a = new A();
would not work and you can use several traits within one class
What you coded made B an inner class of A.
This would let you end up with a composition, since an object of class A can’t be created without an object of class B.
class A {
private B _myObject;
public constructor( B someObject ) {
this._myObject = someObject;
}
}
also this
class A {
private B _object;
public constructor() {
this._object = new B();
}
}
The difference between composition and aggregation is, that an object of a class, which aggregates the objects of another class can exist without those other class objects.
A object of a class, which is a composition of objects of other classes can’t exist without the other class objects.