我是拉勒维尔的新手。Laravel是每次为程序的每个查询创建一个数据库连接,还是使用"Singleton“模式在整个程序中使用相同的数据库对象?该策略对性能有影响吗,特别是对于企业级应用程序?
发布于 2014-12-23 12:00:21
简短回答
不,这不是单身,而是工厂的模式。但是,如果可能的话,同样的连接将被重用,并且您不会手动请求它来重新连接。没有性能上的冲击。
长答案
在请求生命周期的开始,在app/bootstrap/start.php中创建了一个Illuminate\Foundation\Application实例。此服务器作为IoC容器。
在创建应用程序后不久,将加载所有服务提供者。服务提供者在app/config/app.php中定义。
'providers' => array(
// ...
'Illuminate\Database\DatabaseServiceProvider',
// ...
),让我们看看Illuminate\Database\DatabaseServiceProvider,好吗?重要的部分是register函数。
$this->app->bindShared('db', function($app)
{
return new DatabaseManager($app, $app['db.factory']);
});DatabaseManager的一个实例被绑定到db。此实例将在整个请求中保持不变,并将用于每个数据库请求。
“反向”方向的例子
说你打电话
DB::table('users')->get();首先,DB 立面将解析到使用bindShared('db')绑定到DatabaseServiceProvider中的DatabaseManager实例。
protected static function getFacadeAccessor() { return 'db'; }然后转发table('users')调用,因为Database Manager中不存在该方法
public function __call($method, $parameters)
{
return call_user_func_array(array($this->connection(), $method), $parameters);
}在$this->connection()的返回值上调用它。
public function connection($name = null)
{
list($name, $type) = $this->parseConnectionName($name);
// If we haven't created this connection, we'll create it based on the config
// provided in the application. Once we've created the connections we will
// set the "fetch mode" for PDO which determines the query return types.
if ( ! isset($this->connections[$name]))
{
$connection = $this->makeConnection($name);
$this->setPdoForType($connection, $type);
$this->connections[$name] = $this->prepare($connection);
}
return $this->connections[$name];
}使用if (!isset($this->connections[$name])),它将检查连接是否已经建立,如果没有,只会建立一个新的连接。
然后返回连接,然后执行table('users')->get()。
https://stackoverflow.com/questions/27182207
复制相似问题