Search code examples
phpdependency-injectionpsr-11

Why doesn't PHP PSR-11 Container provide methods to set dependencies?


if I develop a library that wants to take advantage of a Dependency Container I think that the container implementation (php-di, symfony/dependency-injection, etc.) should be decided by the library's user that, eventually, passes it to me, for example in the constructor of my classes, as follows:

public function __construct(string param, ?ContainerInterface $container = null)
{
    $this->param = $param;
    $this->container = $container;
}

Now, if I would like to add an entry to the container how can I do it in a way that is compatible across different PSR-11 container implementations if the specification does not provide a common method? With php-di I would have just called the set method:

public function __construct(string param, ?ContainerInterface $container = null)
{
    $this->param = $param;
    $this->container = $container; // I know it's a php-di container
    $myDependency = Factory::buildMyDependency(); // dependency not instantiable through "new" keyword
    $this->container->set(MyDependency::class, $myDependency)
}

Taking a step back, what should be the way to share a container between many libraries that live together? Am I missing something? I don't think that it's advisable that each library brings its own container implementation.

Thank you in advance.


Solution

  • I stumbled across the same question and was also surprised that the set method is not included.

    The reason for this is explained in this document here: https://www.php-fig.org/psr/psr-11/meta/#31-goals

    In short: The target audience for the container interface are authors of libraries or frameworks and not authors of concrete applications where the application itself is responsible for filling the container. That's the reason why there are no setter methods.