Maaz Rehman Maaz Rehman - 4 years ago 185
PHP Question

Difference between aggregation and dependency injection

I have recently studied dependency injection design pattern .

class User
{

private $db;

public function __construct(Database $db)
{
$this->$db = $db;
}

}


I can not help but wonder that is the same thing that i learned in aggregation. Please do correct me if I am wrong . I know goals of dependency injection and aggregation are different . Is there anything that I am missing ?

Answer Source

Aggregation is a form of object composition. It has nothing to do with dependency injection.

In the other hand, dependency injection isn't about how objects are associated with but how to get other objects (dependencies) into a particular object. Dependencies could be aggregates, services, repositories, validators, literals...

Usually, in strongly-typed languages, dependencies are introduced as interfaces to avoid coupling your objects to implementation details. In the opposite side, in dynamically-typed languages, conventions and a strong documentation do the trick to build up a good and tightly-coupled dependency graph.

Note that a database couldn't be an aggregate. Not all associations are considered to be aggregation, while you could consider an injected dependency.

Anyway, there's some design smell in your reasoning: an user shouldn't depend on a database, but a data layer / data mapping layer would be a better candidate to be injected into your user entity if you're going to implement something like active record pattern.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download