Use Singleton Patern in Slim Framework

Hello,
I encounter a problem to retrieve a single instance of a class set as singleton.

For example, my singleton is simple …

class SingletonClass {

private $name = null;
private static $_instance;

private function __construct(){
$this->name = ‘FOO’;
}

public static function getInstance(){
if( true === is_null( self::$_instance ) )
{
echo “getInstance SINGLETON NEW Instance
”;
self::$_instance = new self();
}
return self::$_instance;
}

public function setName($string){
$this->name = $string;
}

public function getName(){
return $this->name;
}
}

##################

My singleton class works very well …
if I instantiate 2 objects “Singleton” … this is the same object that is returned.

example:

equire ‘Slim/Slim.php’;
require ‘myclass/SingletonClass.php’;

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->singleton = SingletonClass::getInstance();

// GET route
$app->get(
’/singleton’,
function () use ($app){

    echo "<h3>Primary Objet | app->singleton->getName() </h3>";
    
    echo $app->singleton->getName();
    $app->singleton->setName('BAR');
    echo "<h3>SetName('BAR')</h3>";

    echo "<h3>app->singleton->getName()</h3>";
    echo $app->singleton->getName();

    echo "<hr>";

     $S2 = SingletonClass::getInstance();
     echo "<h3>Second Objet | $2->getName()</h3>";
     echo $S2->getName();

}

);

$app->run();

RESULT on http://slim2.local/singleton

getInstance SINGLETON NEW Instance
Primary Objet | app->singleton->getName()
FOO
SetName(‘BAR’)
app->singleton->getName()
BAR

Second Objet | $2->getName()
BAR

But if I try to do this from a different route, for example http: //slim2.local/singletonbis with the following code

$app->get(
’/singletonbis’,
function () use ($app){
echo “

app->singleton->getName()

”;
echo $app->singleton->getName();
echo “
”;
}
);

The result is different …
it instantiates a new object “singleton”

Result:

getInstance SINGLETON NEW Instance
app->singleton->getName()
FOO

I would like the getName function returns me “BAR” and not “FOO”

What change has made in my code … so I can have the same object when I change the url router?

Damien

You mean you want to remember the state of the singleton between the 2 requests?

yes that’s what I want

That has nothing to do with Slim.

PHP runs once per page request. So state of an object cannot be passed from one request to another.

You will have to use some sort of a session.

as JoeBengalen pointed out, you’ll have to store the instance in session.

something like this:

public static function getInstance() {
	if (true === is_null($_SESSION['SingletonClass'])) {
		echo "getInstance SINGLETON NEW Instance";
		$_SESSION['SingletonClass'] = new self();
	}
	return $_SESSION['SingletonClass'];
}

Since you haven’t provided any specifics of your session handler, I just used the default PHP method, but I’m sure you can adapt it :wink: