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 ?
Dependency is represented by a dashed arrow starting from the dependent class to its dependency. Multiplicity normally doesn't make sense on a Dependency. Aggregation is same as association and is often seen as redundant relationship.
Dependency can develop between objects while they are associated, aggregated or composed. This kind of relationship develops while one object invokes another object's functionality in order to accomplish some task. Any change in the called object may break the functionality of the caller.
One criticism of inheritance is that it tightly couples parent class with child class. It is harder to reuse the code and write unit tests. That's why most developers prefer dependency injection as a way to reuse code. Dependency injection is a way to inject dependencies into a class for use in its methods.
There are three main styles of dependency injection, according to Fowler: Constructor Injection (also known as Type 3), Setter Injection (also known as Type 2), and Interface Injection (also known as Type 1).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With