我一直在使用Slim Framework,但有一些我无法理解的东西,set和singleton函数之间的区别,例如,如果我想将一个用户模型添加到我的容器中,我可以这样做:
$app->container->set('user', function(){
return new User;
});
Run Code Online (Sandbox Code Playgroud)
或这个:
$app->container->singleton('user', function(){
return new User;
});
Run Code Online (Sandbox Code Playgroud)
它工作正常.所以我想知道这个或那个的用途是什么.谢谢你的帮助.
也许一个例子会有所帮助
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim;
$app->container->set('propA', function(){
static $cnt = 0;
return ++$cnt;
});
$app->container->singleton('propB', function(){
static $cnt = 0;
return ++$cnt;
});
for($i=0; $i<4; $i++) {
// the function "behind" propA is called every time
// when propA is accessed
echo $app->propA, "\r\n";
}
echo "\r\n------\r\n";
for($i=0; $i<4; $i++) {
// the function "behind" propB is called only once
// and the stored return value is re-used
echo $app->propB, "\r\n";
}
Run Code Online (Sandbox Code Playgroud)
版画
1
2
3
4
------
1
1
1
1
Run Code Online (Sandbox Code Playgroud)