Skip to content

Commit

Permalink
[11.x] Add DB::build method (#53464)
Browse files Browse the repository at this point in the history
* Add ability to build a database connection without specifying name

* Add test
  • Loading branch information
stevebauman authored Nov 11, 2024
1 parent b86bf27 commit fc04bbf
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Illuminate/Database/DatabaseManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,21 @@ public function connection($name = null)
return $this->connections[$name];
}

/**
* Build a database connection instance from the given configuration.
*
* @param array $config
* @return \Illuminate\Database\ConnectionInterface
*/
public function build(array $config)
{
return $this->connectUsing(
$config['name'] ?? 'ondemand',
$config,
true,
);
}

/**
* Get a database connection instance from the given configuration.
*
Expand Down
1 change: 1 addition & 0 deletions src/Illuminate/Support/Facades/DB.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
/**
* @method static \Illuminate\Database\Connection connection(string|null $name = null)
* @method static \Illuminate\Database\ConnectionInterface connectUsing(string $name, array $config, bool $force = false)
* @method static \Illuminate\Database\ConnectionInterface build(array $config)
* @method static void purge(string|null $name = null)
* @method static void disconnect(string|null $name = null)
* @method static \Illuminate\Database\Connection reconnect(string|null $name = null)
Expand Down
14 changes: 14 additions & 0 deletions tests/Integration/Database/DatabaseConnectionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,25 @@

use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Events\ConnectionEstablished;
use Illuminate\Database\SQLiteConnection;
use Illuminate\Events\Dispatcher;
use RuntimeException;

class DatabaseConnectionsTest extends DatabaseTestCase
{
public function testBuildDatabaseConnection()
{
/** @var \Illuminate\Database\DatabaseManager $manager */
$manager = $this->app->make(DatabaseManager::class);

$connection = $manager->build([
'driver' => 'sqlite',
'database' => ':memory:',
]);

$this->assertInstanceOf(SQLiteConnection::class, $connection);
}

public function testEstablishDatabaseConnection()
{
/** @var \Illuminate\Database\DatabaseManager $manager */
Expand Down

0 comments on commit fc04bbf

Please sign in to comment.