Skip to content

Commit

Permalink
Add warning about Connection alias service
Browse files Browse the repository at this point in the history
  • Loading branch information
lcharette committed Nov 23, 2023
1 parent 3e4f429 commit 1d273ea
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
13 changes: 7 additions & 6 deletions app/src/Bakery/SetupDbCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use Exception;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Connection;
use Illuminate\Database\Schema\Builder;
use Illuminate\Support\Collection;
use PDOException;
use Psr\Container\ContainerInterface;
Expand Down Expand Up @@ -348,6 +347,13 @@ protected function getEnvPath(): string
* values att all, but it's the easiest way other than
* re-initializing the config class (and actually ArrayFileLoader).
*
* WARNING : This will not update the CONNECTION service !!!
* This is because the connection is already created, and PHP-DI
* has already injected it elsewhere with the old value. We can
* change something in it, but not "it". Updating the connection
* in capsule still works, that's why further command inside bake
* MUST use the config manager.
*
* @param array<string, string> $dbParams The database credentials
*/
protected function updateServices(array $dbParams): void
Expand All @@ -362,10 +368,5 @@ protected function updateServices(array $dbParams): void
$this->capsule->addConnection($dbParams, $dbParams['driver']);
$this->capsule->getDatabaseManager()->setDefaultConnection($dbParams['driver']);
$this->capsule->getDatabaseManager()->purge($dbParams['driver']);

// Update Capsule and Builder services
$connection = $this->capsule->getConnection($dbParams['driver']);
$this->ci->set(Connection::class, $connection);
$this->ci->set(Builder::class, $connection->getSchemaBuilder());
}
}
6 changes: 6 additions & 0 deletions app/src/ServicesProvider/DatabaseService.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ public function register(): array
return $connection->getSchemaBuilder();
},

/**
* WARNING: This service might not be updated if the connection is
* dynamically changed, as the return value is cached by PHP-DI. It
* is recommended to inject "Capsule" instead, and use the
* "getConnection()" method to get the connection.
*/
Connection::class => function (Capsule $db) {
$connection = $db->getDatabaseManager()->getDefaultConnection();

Expand Down

0 comments on commit 1d273ea

Please sign in to comment.