2 minute read

The goal set by the Container PSR is to standardize how frameworks and libraries make use of a container to obtain objects and parameters.

It is important to distinguish the two usages of a container:

  • configuring entries
  • fetching entries

Most of the time, those two sides are not used by the same party. While it is often end users who tend to configure entries, it is generally the framework that fetches entries to build the application.

This is why this interface focuses only on how entries can be fetched from a container.

Non-goals

How entries are set in the container and how they are configured is out of the scope of this PSR. This is what makes a container implementation unique. Some containers have no configuration at all (they rely on autowiring), others rely on PHP code defined via callback, others on configuration files… This standard only focuses on how entries are fetched.

Also, naming conventions used for entries are not part of the scope of this PSR. Indeed, when you look at naming conventions, there are 2 strategies:

  • the identifier is the class name, or an interface name (used mostly by frameworks with an autowiring capability)
  • the identifier is a common name (closer to a variable name), which is mostly used by frameworks relying on configuration.

Both strategies have their strengths and weaknesses. The goal of this PSR is not to choose one convention over the other. Instead, the user can simply use aliasing to bridge the gap between 2 containers with different naming strategies.

Reading from a container

  • The Psr\Container\ContainerInterface exposes two methods: get and has.
  • get takes one mandatory parameter: an entry identifier, which MUST be a string. get can return anything (a mixed value), or throw a NotFoundExceptionInterface if the identifier is not known to the container. Two successive calls to get with the same identifier SHOULD return the same value. However, depending on the implementor design and/or user configuration, different values might be returned, so user SHOULD NOT rely on getting the same value on 2 successive calls.
  • has takes one unique parameter: an entry identifier, which MUST be a string. has MUST return true if an entry identifier is known to the container and false if it is not. If has($id) returns false, get($id) MUST throw a NotFoundExceptionInterface.

Recommended usage

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.

Tags:

Categories:

Updated: