mogarick
mogarick

Reputation: 109

Is Laravel 5.1 App:singleton not working properly?

Given this code, placed in the default file routes.php in Laravel 5.1:

    \App::singleton('CatalogsService', function(){
            return new CatalogsService;
        });   

Route::group(['prefix' => 'catalogs'], function() {
    Route::get('statesmx', function (){       

        return var_dump(app('CatalogsService'));
    });

    Route::get('statesmx2', function() {
        return var_dump(app('CatalogsService'));
    });

    Route::get('statesmx3', function() {
        return var_dump(app('CatalogsService'));
    });

});

Why am I getting a different instance of CatalogsService when navigating to the 3 defined routes?

localhost/catalogs/statesmx dumps:

object(App\Services\Common\CatalogsService)[152]

localhost/catalogs/statesmx2 dumps:

object(App\Services\Common\CatalogsService)[153]

localhost/catalogs/statesmx3 dumps:

object(App\Services\Common\CatalogsService)[154]

I was expecting to get the same Object Reference Id.

The only way to get the same reference is by adding the next code before the Route::group....

app('CatalogsService');

when I do it the 3 routes dump the same object reference:

object(App\Services\Common\CatalogsService)[106]

I don't get it why is this happening. For me it looks Laravel Singleton is not working properly unless there's something I'm missing about the way a Singleton in Laravel works.

Thank you in advance for any help or hint on this matter.

PD: I'm new to Laravel.

Upvotes: 1

Views: 1280

Answers (1)

Ismail RBOUH
Ismail RBOUH

Reputation: 10460

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object...

Therefore, each time you navigate between routes (each Request), the app creates a new instance that will be used across all the application. Even if you get the same object reference between requests it's not the same instance.

Singleton means: Create Single Object Instance for Each Request.

From the Laravel Doc:

The singleton method binds a class or interface into the container that should only be resolved one time, and then that same instance will be returned on subsequent calls into the container.

The best place to bind a singleton is inside the register method of the AppServiceProvider.

$this->app->singleton('CatalogsService', function ($app) {
     return new CatalogsService;
});

Good Luck.

Upvotes: 1

Related Questions