From fc04bbf23f656b17a84598a1ca4e9d9ae7dee568 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Mon, 11 Nov 2024 15:38:24 -0500 Subject: [PATCH] [11.x] Add `DB::build` method (#53464) * Add ability to build a database connection without specifying name * Add test --- src/Illuminate/Database/DatabaseManager.php | 15 +++++++++++++++ src/Illuminate/Support/Facades/DB.php | 1 + .../Database/DatabaseConnectionsTest.php | 14 ++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/src/Illuminate/Database/DatabaseManager.php b/src/Illuminate/Database/DatabaseManager.php index cf408bc6878..3f8f4a90173 100755 --- a/src/Illuminate/Database/DatabaseManager.php +++ b/src/Illuminate/Database/DatabaseManager.php @@ -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. * diff --git a/src/Illuminate/Support/Facades/DB.php b/src/Illuminate/Support/Facades/DB.php index 80e14dcf9a5..c97133416d3 100644 --- a/src/Illuminate/Support/Facades/DB.php +++ b/src/Illuminate/Support/Facades/DB.php @@ -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) diff --git a/tests/Integration/Database/DatabaseConnectionsTest.php b/tests/Integration/Database/DatabaseConnectionsTest.php index dc6b37aa6db..f12bb0fe209 100644 --- a/tests/Integration/Database/DatabaseConnectionsTest.php +++ b/tests/Integration/Database/DatabaseConnectionsTest.php @@ -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 */