我从这个问题中了解到,您希望动态创建datbase连接,以便可以像这样为动态连接创建一个类
<?php namespace App\Database;
use Config;
use DB;
class OTF {
/**
* The name of the database we're connecting to on the fly.
*
* @var string $database
*/
protected $database;
/**
* The on the fly database connection.
*
* @var \Illuminate\Database\Connection
*/
protected $connection;
/**
* Create a new on the fly database connection.
*
* @param array $options
* @return void
*/
public function __construct($options = null)
{
// Set the database
$database = $options['database'];
$this->database = $database;
// Figure out the driver and get the default configuration for the driver
$driver = isset($options['driver']) ? $options['driver'] : Config::get("database.default");
$default = Config::get("database.connections.$driver");
// Loop through our default array and update options if we have non-defaults
foreach($default as $item => $value)
{
$default[$item] = isset($options[$item]) ? $options[$item] : $default[$item];
}
// Set the temporary configuration
Config::set("database.connections.$database", $default);
// Create the connection
$this->connection = DB::connection($database);
}
/**
* Get the on the fly connection.
*
* @return \Illuminate\Database\Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Get a table from the on the fly connection.
*
* @var string $table
* @return \Illuminate\Database\Query\Builder
*/
public function getTable($table = null)
{
return $this->getConnection()->table($table);
}
}
然后,在用户提交连接设置后,您可以调用它
// Using the same host/passwword/etc, just changing databases
$otf = new App\Database\OTF([
'driver' => 'pgsql',
'database' => 'puppies',
'username' => 'jack',
'password' => 'the-cute-dog'
]);
// Get the users table
$users = $otf->getTable('users');
// Find the first user in the table
$first_user = $users->first();
https://lukevers.com/2015/03/25/on-the-fly-database-connections-with-laravel-5
或者,如果您希望将其作为应用程序的安装程序,则应将这些连接设置保存到应用程序根文件夹上的.env文件中
How to change variables in the .env file dynamically in Laravel?