Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel IoC and singleton pattern

I'm trying to use Laravel IoC by creating a singleton object. I'm following the pattern from tutorial as below. I have put a Log message into object (Foobar in this example) constructor and I can see that object is being created every time I refresh page in browser. How is the singleton pattern meant for Laravels IoC? I understood that its shared object for entire application but its obviously being created every time its requested by App:make(...) Can someone explain please. I thought I would use the singleton pattern for maintaining shared MongoDB connection.

App::singleton('foo', function()
{
    return new FooBar;
});
like image 551
David Marko Avatar asked Jun 27 '13 19:06

David Marko


1 Answers

What has been said in Laravel Doc

Sometimes, you may wish to bind something into the container that should only be resolved once, and the same instance should be returned on subsequent calls into the container:

This is how you can bind a singleton object and you did it right

App::singleton('foo', function()
{
    return new FooBar;
});

But, the problem is, you are thinking about the whole process of the request and response in the wrong way. You mentioned that,

I can see that object is being created every time I refresh page in browser.

Well, this is normal behaviour of HTTP request because every time you are refreshing the page means every time you are sending a new request and every time the application is booting up and processing the request you've sent and finally, once the application sends the response in your browser, it's job is finished, nothing is kept (session, cookie are persistent and different in this case) in the server.

Now, it has been said that the same instance should be returned on subsequent calls, in this case, the subsequent calls mean that, if you call App::make(...) several times on the same request, in the single life cycle of the application then it won't make new instances every time. For example, if you call twice, something like this

App::before(function($request)
{
    App::singleton('myApp', function(){ ... });
});

In the same request, in your controller, you call at first

class HomeController {
    public function showWelcome()
    {
        App::make('myApp'); // new instance will be returned
        // ...
    }
}

And again you call it in after filter second time

App::after(function($request, $response)
{
    App::make('myApp'); // Application will check for an instance and if found, it'll  be returned
});

In this case, both calls happened in the same request and because of being a singleton, the container makes only one instance at the first call and keeps the instance to use it later and returns the same instance on subsequent calls.

like image 197
The Alpha Avatar answered Oct 09 '22 01:10

The Alpha