I've been working with Slim Framework but there is something I cannot understand, the difference between set and singleton functions, by example, if I want to add a user model to my container I can do this:
$app->container->set('user', function(){
return new User;
});
or this:
$app->container->singleton('user', function(){
return new User;
});
And It works ok. So I'm wondering what's the point of use one or another. Thanks for your help.
Maybe an example will help
<?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, "
";
}
echo "
------
";
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, "
";
}
prints
1
2
3
4
------
1
1
1
1