Moh*_*rma 3 database-design laravel
我是Laravel的新手。Laravel是否每次为程序的每次查询创建一个数据库连接,还是使用“ Singleton”模式在整个程序中使用相同的数据库对象?该策略是否会对性能产生影响,尤其是对于企业级应用程序?
不,这不是单例,而是工厂模式。但是,如果可能的话,相同的连接将被重用,您无需手动请求重新连接。不会影响性能。
在请求生命周期的开始app/bootstrap/start.php,Illuminate\Foundation\Application就创建了一个实例。该服务器作为IoC容器。
创建应用程序后不久,将加载所有服务提供商。服务提供商在app/config/app.php
'providers' => array(
// ...
'Illuminate\Database\DatabaseServiceProvider',
// ...
),
Run Code Online (Sandbox Code Playgroud)
让我们来看看Illuminate\Database\DatabaseServiceProvider吗?重要的是register功能
$this->app->bindShared('db', function($app)
{
return new DatabaseManager($app, $app['db.factory']);
});
Run Code Online (Sandbox Code Playgroud)
的实例DatabaseManager绑定到db。该实例在整个请求中将保持不变,并将用于每个数据库请求。
说你打电话
DB::table('users')->get();
Run Code Online (Sandbox Code Playgroud)
首先,DB 外观将解析为DatabaseManager在DatabaseServiceProvider使用中绑定的实例bindShared('db')
protected static function getFacadeAccessor() { return 'db'; }
Run Code Online (Sandbox Code Playgroud)
然后,该table('users')呼叫将被转发,因为该方法不存在于Database Manager
public function __call($method, $parameters)
{
return call_user_func_array(array($this->connection(), $method), $parameters);
}
Run Code Online (Sandbox Code Playgroud)
在的返回值上调用 $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];
}
Run Code Online (Sandbox Code Playgroud)
使用if (!isset($this->connections[$name]))它可以检查连接是否已经建立,如果没有建立连接就只能建立一个新的连接。
然后,它返回连接table('users')->get()并将被执行。
| 归档时间: |
|
| 查看次数: |
1382 次 |
| 最近记录: |