本文档描述了依赖注入容器的通用接口。
ContainerInterface设置的目标是标准化框架和库如何使用容器来获取对象和参数(在本文档的其余部分中称为条目)。
本文档中的关键词“必须”,“必须”,“必需”,“应该”,“不应该”,“应该”,“不应该”,“推荐”,“可以”和“可选”按照RFC 2119中的描述进行解释。
本文档中的单词实现者将被解释为在依赖注入相关的库或框架中实现ContainerInterface的人。依赖注入容器(DIC)的用户称为用户。
1 规格
1.1 基础知识
1.1.1 条目标识符
条目标识符是至少一个字符的任何PHP合法字符串,用于唯一标识容器中的项目。条目标识符是不透明的字符串,因此调用者不应该假设字符串的结构带有任何语义含义。
1.1.2 从容器中读取
Psr \ Container \ ContainerInterface公开了两个方法:get和has。
get需要一个必需参数:一个条目标识符,它必须是一个字符串。 get可以返回任何内容(混合值),或者如果容器不知道标识符,则抛出NotFoundExceptionInterface。使用相同标识符的两次连续调用应该返回相同的值。但是,根据实现者设计和/或用户配置,可能会返回不同的值,因此用户不应该依赖于在2次连续调用中获取相同的值。
有一个唯一的参数:一个条目标识符,它必须是一个字符串。如果容器已知条目标识符,则必须返回true,否则返回false。如果has($ id)返回false,则get($ id)必须抛出NotFoundExceptionInterface。
1.2 例外情况
容器直接抛出的异常应该实现Psr \ Container \ ContainerExceptionInterface。
使用不存在的id调用get方法必须抛出Psr \ Container \ NotFoundExceptionInterface。
1.3推荐用法
用户不应该将容器传递给对象,以便对象可以检索自己的依赖项。这意味着容器用作服务定位器,这是一种通常不鼓励的模式。
有关详细信息,请参阅META文档的第4部分。
2 包装
描述的接口和类以及相关的异常作为psr / container包的一部分提供。
提供PSR容器实现的包应声明它们提供psr / container-implementation 1.0.0。
需要实现的项目应该要求psr / container-implementation 1.0.0。
3 接口
3.1. Psr\Container\ContainerInterface
<?php
namespace Psr\Container;
/**
* Describes the interface of a container that exposes methods to read its entries.
*/
interface ContainerInterface
{
/**
* Finds an entry of the container by its identifier and returns it.
*
* @param string $id Identifier of the entry to look for.
*
* @throws NotFoundExceptionInterface No entry was found for **this** identifier.
* @throws ContainerExceptionInterface Error while retrieving the entry.
*
* @return mixed Entry.
*/
public function get($id);
/**
* Returns true if the container can return an entry for the given identifier.
* Returns false otherwise.
*
* `has($id)` returning true does not mean that `get($id)` will not throw an exception.
* It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
*
* @param string $id Identifier of the entry to look for.
*
* @return bool
*/
public function has($id);
}
3.2. Psr\Container\ContainerExceptionInterface
<?php
namespace Psr\Container;
/**
* Base interface representing a generic exception in a container.
*/
interface ContainerExceptionInterface
{
}
3.3. Psr\Container\NotFoundExceptionInterface
<?php
namespace Psr\Container;
/**
* No entry was found in the container.
*/
interface NotFoundExceptionInterface extends ContainerExceptionInterface
{
}