TYPO3-Documentation / TYPO3CMS-Reference-CoreApi

"TYPO3 Explained": Main TYPO3 Core Document: Main classes, Security, TypoScript syntax, Extension API and much more
https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/
22 stars 393 forks source link

Improve Explanation on making things public in DI #4603

Open linawolf opened 4 months ago

linawolf commented 4 months ago

Use the comments by @sbuerk from this ticket: https://github.com/TYPO3-Documentation/TYPO3CMS-Reference-CoreApi/pull/4465

**The second thing is, that this relates to Dependency Injection.

To sum it up:

A class not requiring any autowiring (Constructor Injection, Factory values, injectMethod injection) and are instancable using plain new geword literally does not need anything of this as GU::makeInstance() is cabalbe of creating them using the new keyword. A class which needs autowiring (injection of other services) by the Dependency Injection, but is itself not injected anyway and only retrieved with GU::makeInstance() needs to be marked public: true in the DI, to avoid that the Symfony DI container removes this class because no class needs injection of that class. A class which needs autowriing by the DI and is at least injected in one class throughout active code AND additionally retrieved using GU::makeInstance() can stay public: false, which should be the default if you follow the suggested default extension DI snippet for a extension Services.yaml. Note that this also counts if you want to retrieve a class directly from the DI container (which is internally done in GU::makeInstance() - thus not beeing related to GU::makeInstance() directly but to retrieving manually from the DI container. Different things.

I'd suggest to revise the DI documentation, to enhance the topic about that more slightly and only make a small hint here with a link to the DI section - where it belongs.

A class not needing autowiring, but are available in the DI container and needs to be injected will be injected even with public: false - and GU::makeInstance() cann fallback to a simple new ClassName() without any issue due not having to inject something. Only in case it is never injected and needs autowiring public: true is needed.

Beside that, with TYPO3 v13 the AutoWire PHP Attribute from Symfony can be used instead of configuring it in the Services.yaml/php - which the core already changed recently.**

franzholz commented 4 months ago

The current explanation in the TYPO3 docs is wrong! So the topic should be changed into "fix explanation on DI when to set it public".