Silverstripe 的配置 API 是单例吗?

Is Silverstripe's Configuration API a Singleton?

根据文档,

Configuration API 由于三个属性 API:

可以被视为与 SilverStripe 系统中的其他形式的变量分开
Configuration is per class, not per instance.
Configuration is normally set once during initialization and then not changed.
Configuration is normally set by a knowledgeable technical user, such as a developer, not the end user.

问题是配置 API 单例?

它的行为类似于单例,因为对配置 API 的大多数访问都是通过 Config::inst() 进行的,它将始终 return 当前活动的 Config 实例。此实例将保持不变,直到您决定将其更改为 Config::set_instance($myNewConfigInstance)

所以是的,那里实现了单例模式,但您仍然可以有多个 Config 实例(您可以使用它来隔离环境,如测试或其他)。

以下是您如何在代码执行期间切换配置的示例:

// preserve old config
$defaultConfig = Config::inst();
// create a new config
Config::set_instance(new Config());

// … do stuff that will use the new config

// switch back to the default config once you're done
Config::set_instance($defaultConfig);