我是Laravel的新手。 Laravel是否每次为程序的每个查询创建一个数据库连接,或者使用“Singleton”模式在整个程序中使用相同的数据库对象?该策略是否会对性能产生影响,尤其是对于企业级应用程序?
答案 0 :(得分:6)
不,它不是单身人士,而是工厂模式。但是,如果可能,将重复使用相同的连接,并且您不会手动请求重新连接。没有性能损失。
在请求生命周期开始时,在app/bootstrap/start.php
中创建Illuminate\Foundation\Application
的实例。这个服务器作为IoC容器。
创建应用程序后不久,将加载所有service providers。服务提供商在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
facade将解析为使用DatabaseManager
DatabaseServiceProvider
中的bindShared('db')
实例
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()
将被执行。