jeudi 26 mai 2016

Singleton Class in Laravel 5

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire