Reputation: 4382
I'm using Laravel Framework version 5.2.32. I wish to create a Singleton class whose object is accessible accross all controllers. I've implemented the class as below.
class SingletonClazz {
private static $instance;
protected function __construct() {
//Do nothing
}
public static function getInstance() {
if (empty(SingletonClazz::$instance)) {
SingletonClazz::$instance = new SingletonClazz();
echo 'Created';
}
else {
echo ', Already created';
}
return SingletonClazz::$instance;
}
}
I'm creating an object of the class as below
class MyController extends Controller {
public function initSingleton() {
SingletonClazz::getInstance();
SingletonClazz::getInstance();
SingletonClazz::getInstance();
}
}
The route.php file is configured as below
Route::group(['prefix' => 'singleton'], function() {
Route::get('/', [
'uses' => 'MyController@initSingleton'
]);
});
When I invoke the URL http://localhost:8080/singleton/initSingleton the result is 'Created, Already created, Already created'. When I invoke the URL again, the result is the same whereas I expect it to be 'Already created, Already created, Already created'
Can you guide on the problems with this implementation.
Upvotes: 3
Views: 8150
Reputation: 4795
Why you didn't use Laravel IoC for implementing singleton?
Jeff Lambert in comments are totally right.
Upvotes: 1
Reputation: 7911
With each request send to the PHP server, it is handled as a blank sheet so it is initializing Lavarel from the beginning. Variables defined in the previous request are not automatically saved to the next one.
It is how PHP is designed, build on top of the HTTP protocol that is also designed this way.
What you can do is store the object in a session:
<?php
session_start();
if(isset($_SESSION['instance'])){
$singleton = $_SESSION['instance'];
} else {
$singleton = SingletonClazz::getInstance();
$_SESSION['instance'] = SingletonClazz::$instance;
}
?>
But then again why would you want that and if so, I really suggest changing your implementation. A singleton is structure code, where you have multiple classes with a similar interface, useless data should not be stored into sessions.
Upvotes: 3