Does the database class in Laravel use "Singleton Pattern"?
I am new to Laravel. Does Laravel design a database connection every time for every program request, or does it use the same database object throughout the entire program using the "Singleton" pattern? Does the strategy have a performance impact, especially for enterprise applications?
source to share
Short answer
No, this is not a singleton, but a factory pattern. However, the same connection will be reused if possible, and you will not manually request it to reconnect. There is no performance hit.
Long answer
At the beginning of the request life cycle, app/bootstrap/start.php
an instance is created Illuminate\Foundation\Application
. These are servers as an IoC container.
All service providers will be downloaded shortly after the application is created . Service providers are defined inapp/config/app.php
'providers' => array(
// ...
'Illuminate\Database\DatabaseServiceProvider',
// ...
),
Let's take a look at Illuminate\Database\DatabaseServiceProvider
, shall we? The important part is the functionregister
$this->app->bindShared('db', function($app)
{
return new DatabaseManager($app, $app['db.factory']);
});
The instance is DatabaseManager
bound to db
. This instance will remain unchanged throughout the request and will be used for every database request.
Example from the "reverse" direction
Say what you are calling
DB::table('users')->get();
First, the db
facade will be resolved to an instance DatabaseManager
that binds to DatabaseServiceProvider
usingbindShared('db')
protected static function getFacadeAccessor() { return 'db'; }
The call is then table('users')
forwarded because the method does not exist inDatabase Manager
public function __call($method, $parameters)
{
return call_user_func_array(array($this->connection(), $method), $parameters);
}
It is called for the return value $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];
}
With the help if (!isset($this->connections[$name]))
it checks if the connection is already established and if there will only be a new connection if not.
Then it returns the connection and table('users')->get()
will be executed.
source to share