3

In a controller's execute method, has there been any clear guidance from the Magento core team if client developers should

  1. Be using the individual PageFactory, JsonFactory, RawFactory, etc objects

  2. Or using the more generic Magento\Framework\Controller\ResultFactory object along with the ResultFactory::_TYPE constants

when they want to instantiate an object to return?

If you're not familiar with the issues/confusion around this, I'm talking about the things in the following post. It's not clear if, going forward, Magento's supporting all these methods, or if there's a particular style/technique they prefer (and will support) going forward.

2 Answers 2

2

Both methods will be supported in foreseeable future.

Generic factory was introduced first. It's easy to work with it especially when your action controller might return different result types depending on request data.

Specific factory types were introduced to solve problems with type safety and auto-complete. It's less convenient to work with specific factories (1 constructor dependency per return type), so generic factory was kept as an alternative.

Idea to add specific factory methods to generic factory for each result type is being discussed now. It will solve both problems: convenience and type-safety.

5

I always favor the specific individual factories, because of the following benefits:

  • They give proper method auto-completion on the created result object without a PHPDoc type hint (once the factory has been generated). A PHPDoc type hint can be used to work around that, but many comments become lies over time when the implementation changes, but the comments are not updated.
  • The result types that the action controller might return are clear to see by looking at the constructor parameters.
  • Less coupling to implementation details of the generic ResultFactory (e.g. the type code constants).
  • Less coupling with the parent Action class by relying on protected properties, so one less potential breaking point during upgrades.
  • Easier to write readable tests (no willReturnMap() for a mockResultFactory is required).
1
  • really good points, although I currently prefer to rely on the factory. If, for some reason, the implementation changes, I hopefully still get the right (maybe new) object as I think, that's what factories are made for. Maybe you still are right since the factory could actually serve non result Interface compliant object, but that should be taken care of in the core I think Commented Mar 18, 2016 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.