7

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;
});
4

2 回答 2

34

里面说了什么Laravel Doc

有时,您可能希望将某些内容绑定到只应解析一次的容器中,并且应在随后对容器的调用中返回相同的实例:

这就是绑定singleton对象的方法,而且你做得对

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

但是,问题是,你正在以错误的方式思考和的整个过程requestresponse你提到过,

我可以看到每次在浏览器中刷新页面时都会创建该对象。

好吧,这是HTTP请求的正常行为,因为每次刷新页面意味着每次发送新请求,每次应用程序启动并处理您发送的请求,最后,一旦应用程序发送响应在您的浏览器中,它的工作已经完成,服务器中没有保留任何内容(会话,cookie 在这种情况下是持久的并且不同)。

现在,有人说the same instance should be returned on subsequent calls,在这种情况下,后续调用意味着,如果您App::make(...)在同一个请求上多次调用,在应用程序的单个生命周期中,它不会每次都创建新实例。例如,如果你打电话两次,像这样

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

在同一个请求中,在您的控制器中,您首先调用

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

你再次在after过滤器中调用它

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

在这种情况下,两个调用都发生在同一个请求中,并且由于是单例,容器在第一次调用时只创建一个实例,并保留该实例以供以后使用,并在后续调用中返回相同的实例。

于 2013-06-28T03:13:07.250 回答
-1

它旨在在整个应用程序实例中多次使用。每次刷新页面时,它都是应用程序的一个新实例。

查看更多信息和实际用法:http ://codehappy.daylerees.com/ioc-container

它是为 L3 编写的,但同样适用于 L4。

于 2013-06-27T21:07:59.053 回答