Dependency Injection Breaks Encapsulation

This either makes no sense or you do not understand DI. I cannot tell which.

$objPerson = new Person(new Address);

In what way is this “not interchangeable”? It’s very interchangable…

$objPerson = new Person(new Address);
$objPerson = new Person(new BusinessAddress);
$objPerson = new Person(new POBox);

In this example with DI when I call $objPerson->getData(), if the address object is used it’s entirely polymorphic. Using your singleton class it is not.

You still haven’t explained how this violates encapsulation: $objPerson = new Person(new Address); In this example the Person object encapsulates the address object. Saying this breaks encapsulation is factually incorrect.

This may seem crazy to you, but why is it more crazy than the idea that inheritance breaks encapsulation?

This is well documented in our field and all you’re doing here is showing your ignorance. Please read the very highly regarded Gang of Four Design Pattens book. Alternatively, here are a few articles you may find interesting:

http://blogs.perl.org/users/sid_burn/2014/03/inheritance-is-bad-code-reuse-part-1.html
http://www.developer.com/design/article.php/3525076/Encapsulation-vs-Inheritance.htm
http://users.csc.calpoly.edu/~jdalbey/305/Lectures/ExtendsIsEvil.html

By implementing DI I am changing this to “perform this operation, and use this other object in your implementation”. This then exposes the implementation to the outside world, and by exposing the implementation you are violating encapsulation.

The “outside” world you talk of is a much higher level of the application. The person object must be constructed somewhere. Is this true of all constructor arguments? How about method arguments? If the above “breaks encapsulation” so does $objPerson>getData("person_id=1234"); because the calling code knows about the argument. Knowing that something is required, is not the same as knowing how it is used.

You clearly have a fundamental misunderstanding of encapsulation. As we went through in the last thread, please go away and read the related literature before coming here and offering your own skewed interpretation of these concepts or provide references to back up your claims. You repeatedly fail to produce working, minimal code examples or references and this is why people struggle to take your posts seriously.

It would be a waste of time giving code samples that never actually existed in my framework

No it would not. As it would be unbiased, decoupled for anything else, minimal and easier to follow.

1 Like