container icon indicating copy to clipboard operation
container copied to clipboard

Add generics to ContainerInterface (new proposal)

Open loic425 opened this issue 1 year ago • 2 comments

Inspired by #44

I've tried @nicolas-grekas' proposal but I do not have autocompletion without adding "@param" annotation.

loic425 avatar Jan 11 '24 09:01 loic425

Now works well with PHPStan https://phpstan.org/r/03c35ee8-10f5-490c-a263-37855651e35d And Psalm https://psalm.dev/r/8b5c98aa39

snapshotpl avatar Feb 05 '24 15:02 snapshotpl

I'm a big fan of generics and I think a container that implements this functionality should feel free to apply this to their container implementation. I think applying them here however doesn't quite make sense and goes against the spirit of this PSR.

For one PSR-11 says:

An entry identifier is an opaque string, so callers SHOULD NOT assume that the structure of the string carries any semantic meaning.

Which to me heavily implies that a class string key should not automatically result in an instance of that class. By typehinting ($id is class-string<T> ? T : mixed) we are requiring the return type to be an instance of a class if the key looks like a class string and preventing valid usage like ->get('\Exception') // 'Exception is the base class for all user exceptions'. ($id is class-string<T> ? T|mixed : mixed) could work instead, but I still think that goes against the quoted text by implying there's some potential structure to keys.

What's more, PSR-11 recommends:

Users SHOULD NOT pass a container into an object so that the object can retrieve its own dependencies. This means the container is used as a Service Locator which is a pattern that is generally discouraged.

And I'd argue having generics on the base get method implies the opposite.

KorvinSzanto avatar Feb 15 '24 21:02 KorvinSzanto