dimanche 22 mai 2022

Symfony5 non-service classes - how to get services (like EntityManager)

The problem:

producer A produces 50 products

producer A sells its products through 300+ resellers across the world

each reseller demands the product sheets in a different structure/format/attributes etc.

Because:

I need 300+ methods to build each reseller's format, looped 50 times (for each product)

I guess that:

placing all 300+ methods in one class (in one 5000+ lines service class) is ugly, anti-design etc.

creating 300+ services (SellerX, each containing a method to create the product sheet) and auto-wiring them in the caller service __construct() is also no-go (the caller service being the one to loop the 300 methods 50 times)

Remaining option: strategy design pattern, with an interface class to be implemented 300+ times for each of the 300+ SellerX (to implement the method createProductSheet() in 300+ non-service classes). But how should the 300+ classes be built and used, in order to benefit from Symfony's EntityManager service and other useful Services that I need?

The big problem with this approach is that, in the calling code, I would somehow need to (first) instantiate a SellerX object with the NEW keyword (dynamic instantiation) AND pass each required service as argument (which would again turn ugly when tens of extra services are required in any of the createProductSheet() methods; furthermore, not all SellerX methods need all the services that would be passed as a bulk).

Whether the 300+ implementations of the method createProductSheet() are Singletons, static methods classes, or regular classes (non-singletons, non-static methods), the main problem is the same: I cannot use dependency injection.

Is there a way to access services like EntityManager from custom classes? From the Kernel? How?

Or, perhaps, is there any other possibility?

Aucun commentaire:

Enregistrer un commentaire