php-fig / container

MIT License
9.95k stars 53 forks source link

Add generics to ContainerInterface (new proposal) #50

Open loic425 opened 10 months ago

loic425 commented 10 months ago

Inspired by #44

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

snapshotpl commented 9 months ago

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

KorvinSzanto commented 8 months ago

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.