[英]How Is This Function Working? I Can't Understand Exactly What is Going On
Here is a function definition of Set Helper
class 这是Set
Helper
类的函数定义
public function singleton($key, $value)
{
$this->set($key, function ($c) use ($value) {
static $object;
if (null === $object) {
$object = $value($c);
}
return $object;
});
}
and in this class the above mentioned function will be called like 在这个类中,上面提到的函数将像
// Default environment
$this->container->singleton('environment', function ($c) {
return \Slim\Environment::getInstance();
});
where $this->container
represents the Set
helper class. 其中
$this->container
表示Set
帮助器类。
This appears to be an example of singleton factory using a plugin-strategy. 这似乎是使用插件策略的单例工厂的示例。
The API user declares "When I ask for the environment
object, use the function function ($c) { return Slim\\Environment::getInstance() }
to generate it." API用户声明“当我请求
environment
对象时,请使用函数function ($c) { return Slim\\Environment::getInstance() }
生成它。” The singleton
method then takes care to ensure the API user only ever gets back the single instance of the environment
object. 然后,
singleton
方法要确保API用户仅取回environment
对象的单个实例。
Mechanically, the singleton
method associates a closure with a key. 从机械上讲,
singleton
方法将闭包与键关联。 The closure manufactures a singleton object, given an anonymous function plug-in to actually do the instantiation. 给定一个匿名函数插件来实际执行实例化,闭包将创建一个单例对象。
$value
is the anonymous function and is responsible for whatever needs to go on to generate an instance of the object to become a singleton. $value
是匿名函数,它负责生成对象实例以成为单例的一切工作。 singleton
is responsible for ensuring that instantiation is every called once. singleton
负责确保实例化每次被调用一次。
Side note: the difference between a closure and an anonymous function is meaninful in understanding what's going on with this method. 旁注: 闭包和匿名函数之间的区别在理解此方法的含义方面是有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.