AD0-E724 · Question #8
When is it appropriate to use a "preference" in 'di.xml' instead of a plugin?
The correct answer is D. When you need to completely replace an implementation of a class or interface for all subsequent. A preference in di.xml is the right tool when you need to completely swap out an entire class or interface implementation - it tells Magento's DI container "use this class instead of that one" globally, making it ideal for full replacements (D). Why the distractors are wrong…
Question
When is it appropriate to use a "preference" in 'di.xml' instead of a plugin?
Options
- AWhen you need to add code that executes after any product is saved.
- BWhen you need to modify the return value of a protected method.
- CWhen you need to modify the arguments of a public method.
- DWhen you need to completely replace an implementation of a class or interface for all subsequent
How the community answered
(33 responses)- A3% (1)
- B18% (6)
- C9% (3)
- D70% (23)
Explanation
A preference in di.xml is the right tool when you need to completely swap out an entire class or interface implementation - it tells Magento's DI container "use this class instead of that one" globally, making it ideal for full replacements (D).
Why the distractors are wrong:
- (A) Executing code after a product is saved is an event/observer pattern use case, not a DI preference or plugin.
- (B) Plugins cannot intercept
protectedmethods at all, but the solution there would be class rewrite via preference - however, modifying just return values of protected methods is better handled by extending the class, not a blanket preference. This option is a trap because it conflates "can't use a plugin" with "should use a preference." - (C) Modifying public method arguments is exactly what an around or before plugin is designed for - preferences are overkill and create harder-to-maintain override chains.
Memory tip: Think of a preference as a full substitution ("replace the whole thing") and plugins as surgical modifications ("tweak before/after/around"). If you only need to touch one method's behavior, use a plugin; if you need to replace the whole class, use a preference.
Topics
Community Discussion
No community discussion yet for this question.