根据文档,
由于三个属性 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()
,这将始终返回当前活动的Config
实例。此实例将保持不变,直到您决定使用 Config::set_instance($myNewConfigInstance)
进行更改。
所以是的,那里实现了单例模式,但您仍然可以拥有多个Config
实例(您可以使用它来隔离环境,例如测试或其他)。
下面是如何在代码执行期间切换 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);