我正在尝试通过创建单例对象来使用 Laravel IoC。我遵循以下教程中的模式。我已将日志消息放入对象(本例中为 Foobar)构造函数中,每次在浏览器中刷新页面时,我都可以看到该对象正在创建。单例模式对于 Laravel IoC 意味着什么?我知道它是整个应用程序的共享对象,但显然每次 App:make(...) 请求时都会创建它,有人可以解释一下吗?我想我会使用单例模式来维护共享 MongoDB 连接。
App::singleton('foo', function()
{
return new FooBar;
});
最佳答案
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:
这就是绑定(bind) singleton
的方法对象,你做对了
App::singleton('foo', function()
{
return new FooBar;
});
但是,问题是,你正在思考request
的整个过程。和response
以错误的方式。你提到过,
I can see that object is being created every time I refresh page in browser.
嗯,这是 HTTP
的正常行为请求,因为每次刷新页面意味着每次发送新请求,每次应用程序启动并处理您发送的请求,最后,一旦应用程序在浏览器中发送响应,它的工作就是完成后,服务器中不会保留任何内容( session 、cookie 是持久的并且在本例中是不同的)。
现在,据说 the same instance should be returned on subsequent calls
,在这种情况下,后续调用意味着,如果您调用 App::make(...)
在应用程序的单个生命周期中对同一个请求多次创建,那么它不会每次都创建新实例。例如,如果你调用两次,就像这样
App::before(function($request)
{
App::singleton('myApp', function(){ ... });
});
在同一个请求中,您首先在 Controller 中调用
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
});
在这种情况下,两个调用发生在同一个请求中,并且由于是单例,容器在第一次调用时仅创建一个实例,并保留该实例以供以后使用,并在后续调用中返回相同的实例。
关于Laravel IoC 和单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17351658/