magento / magento2

Prior to making any Submission(s), you must sign an Adobe Contributor License Agreement, available here at: https://opensource.adobe.com/cla.html. All Submissions you make to Adobe Inc. and its affiliates, assigns and subsidiaries (collectively “Adobe”) are subject to the terms of the Adobe Contributor License Agreement.
http://www.magento.com
Open Software License 3.0
11.51k stars 9.31k forks source link

Magento2 should have setter dependency injection #3682

Closed degaray closed 8 years ago

degaray commented 8 years ago

There should be a way to inject dependencies and have Magento2 call a setter. Some third party classes are done this way so it would be very good to have this feature. See Symfony3 injection for more idea.

Steps to reproduce

  1. Try to inject into Magento2 a Writer object set with a PNG of width and height equals to 256 using this package: BaconQrCode

    Expected result

  2. It should be a usable object ready to paste the message and get the QR. Instead I will need to create a constructor class actually extending from PNG.

    Actual result

  3. Not feasible
antonkril commented 8 years ago

In magento 2 all objects should be ready for use immediately after instantiation. Also most of our services are immutable, they don't change state after creation. Setter injection contradicts both these concepts, so is not supported.

Setter injection leads to broken encapsulation and temporal coupling. You should not use it in your objects. If you need different instances of one class configured with different dependencies, you can use argument configuration.

You can get more details in post by @alankent: http://alankent.me/2015/03/03/why-i-prefer-constructor-injection-over-setter-or-property-injection/

degaray commented 8 years ago

I agree on that, however, some already made third-party libraries use that principle and it can become handy for using such libraries.

antonkril commented 8 years ago

It's always a good practice to use adapters for third-party system interfaces to allow implementation substitutions and made upgrades easier.